﻿#include <QtWidgets>
#include <QtNetwork>
#include <QtGui/qevent.h>

#include <QTest>
#include <QThread>
//#include "../webview.h"
#include "codeeditor.h"
#include "../auto/ImageParserClass.h"




#include "dialog.h"



#include "cximage/visionmanager.h"

#include "diagramtab.h"

#include "runthread.h"

//#include "calibview/robotcalibdialog.h"
//#include "calibview/cameracalibdialog.h"

#include "modbustcp/modbuswidget.h"

 
qint64 Dialog::g_listID = 0;

QString  getlocationstringx(const QString &strfile)
{
    QString locationstring;
#if defined( Q_OS_WINx )

#else
    QString argv0 = strfile;//QFile::decodeName(QByteArray(strfile));
    QString absPath;

    if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/'))
    {
        /*
        If argv0 starts with a slash, it is already an absolute
        file path.
        */
        absPath = argv0;
    }
    else if (argv0.contains(QLatin1Char('/')))
    {
        /*
        If argv0 contains one or more slashes, it is a file path
        relative to the current directory.
        */
        absPath = QDir::current().absoluteFilePath(argv0);
    }
    else
    {
        /*
        Otherwise, the file path has to be determined using the
        PATH environment variable.
        */
        QByteArray pEnv = qgetenv("PATH");
        QDir currentDir = QDir::current();
        QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":"));
        for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
            if ((*p).isEmpty())
                continue;
            QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
            QFileInfo candidate_fi(candidate);
            if (candidate_fi.exists() && !candidate_fi.isDir()) {
                absPath = candidate;
                break;
            }
        }
    }

    absPath = QDir::cleanPath(absPath);
    if(!absPath.isEmpty())
       return absPath;
    QFileInfo fi(absPath);
    locationstring = fi.exists() ? fi.canonicalFilePath() : QString();
#endif
    if(!locationstring.isEmpty())
        locationstring =QFileInfo(locationstring).absolutePath()+ QLatin1Char('/') +strfile;
    return locationstring;
}

#ifdef CXVISIONPILLOW

#include "HttpHelpers.h"
class HttpHandlerStats : public HttpHandler
{
public:
	Dialog *m_pdialog;
	HttpHandlerStats(QObject* parent = 0,Dialog *pdialog=0) : HttpHandler(parent), m_pdialog(pdialog){}

	virtual bool handleRequest(Pillow::HttpConnection* rq)
	{
		Pillow::HttpServer* server = NULL;
		Pillow::HttpHandler* handler = NULL;

		for (QObject* h = parent(); h != NULL; h = h->parent())
		{
			if (qobject_cast<Pillow::HttpHandler*>(h)) handler = static_cast<Pillow::HttpHandler*>(h);
			else if (qobject_cast<Pillow::HttpServer*>(h)) server = static_cast<Pillow::HttpServer*>(h);
		}
		//////////////////////////////////////////////////////////////////////////
		if(rq->requestMethod() == "POST")
		{
			//m_pdialog->ShowHttpLog(tr(" ")+rq->remoteAddress().toString()+tr("END")
			//	+tr(" requestMethod ")+rq->requestMethod()+tr("END")
			//	+tr(" requestUri ")+rq->requestUri()+tr("END")
			//	+tr(" requestFragment ")+rq->requestFragment()+tr("END")
			//	+tr(" requestPath ")+rq->requestPath()+tr("END")
			//	+tr(" requestQueryString ")+rq->requestQueryString()+tr("END")
 
				//+tr(" HttpVersion:")+rq->requestHttpVersion()
				//+tr(" requestContent ")+rq->requestContent()+tr("END ")
				//+tr(" ContentSize %1 ").arg(rq->requestContent().size())+tr("END ")
				//+tr(" requestUriDecoded ")+rq->requestUriDecoded()+tr("END ")
				//+tr(" requestFragmentDecoded ")+rq->requestFragmentDecoded()+tr("END")
				//+tr(" requestPathDecoded ")+rq->requestPathDecoded()+tr("END")
				//+tr(" requestQueryStringDecoded ")+rq->requestQueryStringDecoded()+tr("END"));

				//m_pdialog->savefile(const QByteArray &qcontent,const QString &qname);
			//	m_pdialog->ShowHttpLog(rq->requestContent()); 
			
			//NEED TO DO CXVISIONAI
                //m_image  = QPixmap::grabWidget(this,this->frameGeometry()).toImage();
                //QString imgFormat(QLatin1String("image/PNG"));
                //QByteArray f(imgFormat.mid(6).toAscii());
                //m_httpsendbuf.clear();
				//QBuffer w(&m_httpsendbuf);
				//w.open(QIODevice::WriteOnly);
				//QImageWriter writer(&w, f.toUpper());
				//if (writer.write(m_image))
				//{
				//	w.close(); 

				//	m_httpsendhead.clear();
				//	m_httpsendhead.reserve(2);
				//	m_httpsendhead << HttpHeader("Content-Type", "image/png");//��ʾͼ��ʹ�� "image/jpeg"
				//	QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
				//	QByteArray etag = md5sum.result().toHex();
				//	m_httpsendhead << HttpHeader("ETag", etag); 
				//} 
				//m_pdialog->GetHttpFile(rq->requestContent());
				
		}
		else
		{
			//////////////////////////////////////////////////////////////////////////
			m_pdialog->ShowHttpLog(tr(" ")+rq->remoteAddress().toString()
				+tr(" ")+rq->requestMethod()
				+tr(" ")+rq->requestUri()
				+tr(" ")+rq->requestFragment()
				+tr(" ")+rq->requestPath()
				+tr(" ")+rq->requestQueryString()
				//+tr(" HttpVersion:")+rq->requestHttpVersion()
				+tr(" ")+rq->requestContent()
				+tr(" ")+rq->requestUriDecoded()
				+tr(" ")+rq->requestFragmentDecoded()
				+tr(" ")+rq->requestPathDecoded()
				+tr(" ")+rq->requestQueryStringDecoded());


		}


		
		if (rq->requestPath() == "/_stats")
		{
			 
			QByteArray result = "Welcome to CxvisionAI's world \r\n  ����δ���ɴ˶��� \r\n";
			if (server != NULL)
			{
				result.append("live connections: ").append(QByteArray::number(server->findChildren<Pillow::HttpConnection*>().size())).append("\n");
			}
			if (handler != NULL)
			{
				result.append("live big file transfers: ").append(QByteArray::number(handler->findChildren<Pillow::HttpHandlerFileTransfer*>().size())).append("\n");
			}

            const QDir cxDir(getlocationstringx("./file"));

			QStringList stfilterlist;

			QStringList filelist =  cxDir.entryList(QDir::AllEntries, QDir::Name);

			int isize = filelist.size();

			for(int i=0;i<isize;i++)
			{
				result.append("<a href=\"http://www.cxvisionai.com/"+filelist.at(i)+"\">http://www.cxvisionai.com/"+filelist.at(i)+"</a>\r\n");
			}
 
			rq->writeResponse(200, HttpHeaderCollection(), result);
			return true;
		}
		else if (rq->requestPath() == "/")
		{

			//////////////////////////////////////////////////////////////////////////

            QString strindex =  getlocationstringx("./file/index.html");
			QFile* file = new QFile(strindex);

			if (!file->open(QIODevice::ReadOnly))
			{
				// Could not read the file?
				rq->writeResponse(403, HttpHeaderCollection(), QString("The requested resource '%1' is not accessible").arg("index.html").toUtf8());
				delete file;
			}
			else
			{
				HttpHeaderCollection headers; 
				headers.reserve(2);
				QString requestPath = QByteArray::fromPercentEncoding(rq->requestPath());
				//////////////////////////////////////////////////////////////////////////
				//getMimeTypeForFilename()
				//if (filename.endsWith(".html", Qt::CaseInsensitive)) return "text/html";
				//if (filename.endsWith(".jpg", Qt::CaseInsensitive)) return "image/jpeg";
				//if (filename.endsWith(".jpeg", Qt::CaseInsensitive)) return "image/jpeg";
				//if (filename.endsWith(".png", Qt::CaseInsensitive)) return "image/png";
				//if (filename.endsWith(".gif", Qt::CaseInsensitive)) return "image/gif";
				//if (filename.endsWith(".css", Qt::CaseInsensitive)) return "text/css";
				//if (filename.endsWith(".js", Qt::CaseInsensitive)) return "text/javascript";
				//if (filename.endsWith(".xml", Qt::CaseInsensitive)) return "text/xml";
				//return "application/octet-stream";
				//////////////////////////////////////////////////////////////////////////
				headers << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
 
				// The file fully fits in the supported buffer size. Read it and calculate an ETag for caching.
				QByteArray content = file->readAll();
				QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(content);
				QByteArray etag = md5sum.result().toHex();
				headers << HttpHeader("ETag", etag);

				if (rq->requestHeaderValue("If-None-Match") == etag)
					rq->writeResponse(304); // The client's cached file was not modified.
				else
					//rq->writeResponse(200, HttpHeaderCollection(), content);
					rq->writeResponse(200, headers, content);

				delete file;
 
 
			} 
			//////////////////////////////////////////////////////////////////////////
			return true;
		}  
		else
		{ 
			m_pdialog->sethttpreqtype(0); 
			if(m_pdialog->sethttplog(rq->requestUri()))
			{
				rq->writeResponse(200, HttpHeaderCollection(), m_pdialog->gethttpreqstring());
				return true;
			} 
		}
		return false;
	}
};

#endif


QProcess proc;
// void* Dialog::hEventWaitFinish = NULL;
Dialog::Dialog(QWidget *parent)
    : QWidget(parent)
{

    m_getfilefinish = 1;
    m_iallfinish = 0;
    m_sendTime.start();

    //settfilefinish();

    m_btimerun = 0;
    m_ibegintime_d =0;
    m_ibegintime_h=0;
    m_ibegintime_m=0;
    m_ibegintime_s=0;
	m_runonce =0;
	m_idownlodtype = 0;
    g_cond.wakeOne();
    m_pmsize = TRANSFOR_SIZE;//1024*500;//1024000;//4096
    m_sqlmain = nullptr;
    m_sqlbrower = nullptr;
    m_imageViewer = nullptr;
    m_ishowtextlinenum = 0;
	m_ilogin = 0;
    m_pcurrentconnect = nullptr;
	
    m_pirc = nullptr;
    m_ptcpClient = nullptr;

    clientProgressBar = new QProgressBar;
    clientStatusLabel = new QLabel(tr("Client ready"));
    //serverProgressBar = new QProgressBar;
    serverStatusLabel = new QLabel(tr("Server ready"));

    ServerTextEdit = new QListWidget;
	ClientTextEdit = new QTextEdit;
    m_editor = new QTextEdit;
	
	CommandEdit = new QLineEdit;
	TimeTextEdit = new QLineEdit;
	adminiEdit =  new QLineEdit;
	
	widgetList = new QListWidget;
	widgetList2= new QListWidget;
    widgetList3= new QListWidget;
    //m_codeeditor = new CodeEditor;

    ServerTextEdit->setMinimumHeight(300);
    ClientTextEdit->setMinimumHeight(50);
	ClientTextEdit->setMaximumHeight(50); 
	 
    widgetList->setMinimumHeight(80);
    widgetList2->setMinimumHeight(80);
    widgetList3->setMinimumHeight(80);

    m_editor->setMinimumHeight(300);
   m_editor->setMaximumHeight(1600);

    ServerstartButton = new QPushButton(tr("服务端开始"));
    ServerstartButton->setMinimumWidth(80);

    ClientstartButton = new QPushButton(tr("客户端开始"));
    ClientstartButton->setMinimumWidth(80);

    MsgButton = new QPushButton(tr("机器人导引"));
    MsgButton->setMinimumWidth(80);

    SendFileButton = new QPushButton(tr("相机标定"));
    SendFileButton->setMinimumWidth(80);

    SaveAutoButton = new QPushButton(tr("保存框架"));
    SaveAutoButton->setMinimumWidth(50);

    CommandButton = new QPushButton(tr("复位"));
    CommandButton->setMinimumWidth(50);
   // CommandButton->setMinimumHeight(80);

    quitButton = new QPushButton(tr("隐藏"));
    quitButton->setMinimumWidth(80);
    quitButton->setMinimumHeight(80);
    adminiButton = new QPushButton(tr("编辑"));
    adminiButton->setMinimumWidth(80);
    adminiButton->setMinimumHeight(80);
    compressButton = new QPushButton(tr("检测预览"));
    compressButton->setMinimumWidth(80);
    compressButton->setMinimumHeight(80);
    addDutyButton = new QPushButton(tr("编辑使能"));
    addDutyButton->setMinimumWidth(80);
    addDutyButton->setMinimumHeight(80);

    SaveParserButton = new QPushButton(tr("保存编译"));
    SaveParserButton->setMinimumWidth(80);
    SaveParserButton->setMinimumHeight(80);
    TestParserButton = new QPushButton(tr("运行编译"));
    TestParserButton->setMinimumWidth(80);
    TestParserButton->setMinimumHeight(80);
    SetValueButton = new QPushButton(tr("设置变量值"));
    SetValueButton->setMinimumWidth(80);
    GetValueButton = new QPushButton(tr("获取变量值"));
    GetValueButton->setMinimumWidth(80);
    ValueEdit = new QLineEdit;
    ValueEdit->setMinimumWidth(50);
    SetEdit = new QLineEdit;
    SetEdit->setMinimumWidth(50);

    buttonBox = new QDialogButtonBox;
    buttonCxBox = new QHBoxLayout;

	layoutbox = new QHBoxLayout;

    parserlayoutbox = new  QHBoxLayout;

	CxConnection::Loadmyfunction();

    buttonBox->addButton(compressButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(adminiButton, QDialogButtonBox::ActionRole);

    //buttonBox->addButton(ServerstartButton, QDialogButtonBox::ActionRole );
    //buttonBox->addButton(ClientstartButton, QDialogButtonBox::ActionRole);

	buttonBox->addButton(addDutyButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::ActionRole);

    buttonCxBox->addWidget(CommandButton );
    buttonCxBox->addWidget(SetValueButton);
    buttonCxBox->addWidget(GetValueButton);
    buttonCxBox->addWidget(ValueEdit);
    buttonCxBox->addWidget(SetEdit);


    buttonCxBox->addWidget(MsgButton );
    buttonCxBox->addWidget(SendFileButton );
    buttonCxBox->addWidget(SaveAutoButton );

    connect(ServerstartButton, SIGNAL(clicked()), this, SLOT(serverStart()));
    connect(ClientstartButton, SIGNAL(clicked()), this, SLOT(clientStart()));

    connect(addDutyButton, SIGNAL(clicked()), this, SLOT(editManage()));
	
    connect(MsgButton, SIGNAL(clicked()), this, SLOT(robotcalibdlg()));
    connect(SendFileButton, SIGNAL(clicked()), this, SLOT(cameracalibdlg()));
    connect(SaveAutoButton, SIGNAL(clicked()), this, SLOT(SaveAutoCreate()));


    connect(CommandButton, SIGNAL(clicked()), this, SLOT(ReSetLayout()));//resetrun
connect(compressButton, SIGNAL(clicked()), this, SLOT(closeflash()));
  //  connect(CommandEdit, SIGNAL(returnPressed()), this, SLOT(sendCommand()));

    connect(quitButton, SIGNAL(clicked()), this, SLOT(ReSetLayout()));

    reconnectTimer.setInterval(8 * 1000);

//	connect(&reconnectTimer, SIGNAL(timeout()), this, SLOT(restart()));
if(0)
{
    layoutbox->addWidget(widgetList);
    layoutbox->addWidget(widgetList2);
    layoutbox->addWidget(widgetList3);
}
parserlayoutbox->addWidget(TestParserButton);
parserlayoutbox->addWidget(SaveParserButton);
//parserlayoutbox->addWidget(SetValueButton);
//parserlayoutbox->addWidget(GetValueButton);
//parserlayoutbox->addWidget(ValueEdit);
//parserlayoutbox->addWidget(SetEdit);
ValueEdit->setText(QString("0"));
SetEdit->setText(QString("doutputvalue"));

connect(SaveParserButton, SIGNAL(clicked()), this, SLOT(SaveParser()));
connect(TestParserButton, SIGNAL(clicked()), this, SLOT(TestParser()));
connect(adminiButton, SIGNAL(clicked()), this, SLOT(ReSetLayout()));


connect(SetValueButton, SIGNAL(clicked()), this, SLOT(SetValue()));
connect(GetValueButton, SIGNAL(clicked()), this, SLOT(GetValue()));

    m_blayout = new QVBoxLayout;

    m_blayout->addStretch(1);
    m_blayout->addSpacing(10);
    m_blayout->addWidget(ServerTextEdit);
    m_blayout->addLayout(parserlayoutbox);
    m_blayout->addWidget(m_editor);
    m_blayout->addWidget(buttonBox);
    m_blayout->addWidget(CommandEdit);

    m_blayout->addWidget(serverStatusLabel);
    m_editor->setFont(QFont("Fixedsys", 16));
    CodeViewIni();
    m_blayout->addWidget(clientProgressBar);
    m_blayout->addWidget(clientStatusLabel);
    m_blayout->addWidget(ClientTextEdit);

	QHBoxLayout *editlayoutbox = new QHBoxLayout;
	editlayoutbox->addWidget(adminiEdit); 
	editlayoutbox->addWidget(TimeTextEdit); 


    m_pvisionview = new visionView("cxvision");
    m_pmanager = m_pvisionview->view();

    //m_pspectrum_input = new SpectrumWidget;
    //m_pspectrum_output = new SpectrumWidget;

    m_diagramtab = new DiagramTab;
    m_tabWidget = new QTabWidget;
    m_tabWidget->addTab(new VisionTab(m_pvisionview), tr("图像分析"));
    m_tabWidget->addTab(m_diagramtab, tr("结构逻辑"));
    //m_tabWidget->addTab(new SpectrumTab(m_pspectrum_output,m_pspectrum_input),tr("audio"));

    //QHBoxLayout *alayout = new QHBoxLayout;
    m_alayout = new QHBoxLayout;

    QVBoxLayout *piclayout = new QVBoxLayout;

    piclayout->addWidget(m_tabWidget);

    piclayout->addLayout(buttonCxBox);
    piclayout->addLayout(editlayoutbox);
    piclayout->addLayout(layoutbox);

    m_alayout->addLayout(piclayout);
    m_alayout->addLayout(m_blayout);
    setLayout(m_alayout);

    QObject::connect(m_diagramtab, SIGNAL(SelectState(const QString &)),m_pmanager, SLOT(SetOptStateName(const QString &)));
    QObject::connect(m_diagramtab, SIGNAL(SelectConnect(const QString &)),m_pmanager, SLOT(SetOptConnectName(const QString &)));
    QObject::connect(m_diagramtab, SIGNAL(SelectConnect(const QString &)),m_pmanager, SLOT(loadconnectstring()));
    QObject::connect(m_diagramtab, SIGNAL(SelectState(const QString &)),m_pmanager, SLOT(loadstatestring()));
    QObject::connect(m_pmanager, SIGNAL(OperationModelList(const QStringList&)),m_diagramtab, SLOT(AddModelList(const QStringList&)));
    QObject::connect(m_pmanager, SIGNAL(OperationModelConnectList(const QStringList&)),m_diagramtab, SLOT(AddModelConnectList(const QStringList&)));
    QObject::connect(m_pmanager, SIGNAL(RunState(const QString&)),m_diagramtab, SLOT(SetModelColor(const QString&)));
  //  QObject::connect(m_pmanager, SIGNAL(RunState(const QString&)),m_diagramtab, SLOT(HighlighterDebugModel(const QString&)));
    QObject::connect(m_pmanager, SIGNAL(RunConnect(const QString&)),m_diagramtab, SLOT(SetModelConnectColor(const QString&)));
  //  QObject::connect(m_pmanager, SIGNAL(RunConnect(const QString&)),m_diagramtab, SLOT(HighlighterDebugModel(const QString&)));

    QObject::connect(m_pmanager, SIGNAL(runopt(const QString&)),m_diagramtab, SLOT(SetModelColor(const QString&)));
    QObject::connect(m_pmanager, SIGNAL(runopt(const QString&)),m_diagramtab, SLOT(HighLightModelColor(const QString&)));

    QObject::connect(m_pmanager, SIGNAL(runopt(const QString&)),m_diagramtab, SLOT(AddModelConnectB(const QString&)));
    QObject::connect(m_pmanager, SIGNAL(runoptover(const QString&)),m_diagramtab, SLOT(AddModelConnectA(const QString&)));
  //QObject::connect(m_pmanager, SIGNAL(runoptover(const QString&)),m_diagramtab, SLOT(NormalModelColor(const QString&)));

    QObject::connect(m_pmanager, SIGNAL(StateClear()),m_diagramtab, SLOT(deleteAllItem()));
    QObject::connect(m_pmanager, SIGNAL(signals_GetConnectString(const QString&)),m_editor, SLOT(setText(const QString&)));
    QObject::connect(m_pmanager, SIGNAL(signals_GetStateString(const QString&)),m_editor, SLOT(setText(const QString&)));


   QString qstr = m_pmanager->initialparser();//cxvision important
   if(qstr!="")
        ShowLog(nullptr,qstr);
   else
       ShowLog(nullptr,"initial parser ok");
    ClientGetTotalBytes =  -1;
    ServerGetTotalBytes = - 1;
    
   m_icurconnect = -1;
   m_iconnecttype = 0;
	
   m_idutytype = 0;
   m_reqstring =tr("file_");

   m_ireq = 0;
   m_pagesnum = 0;
   m_pagelevel = 0;
   m_iviewuse = 0;
   m_pagevisitnum  = 3;

   QString qstrtime = QTime::currentTime().toString("Uhhmmsszzz");//U123359375C123415656
   m_useradmin = qstrtime;
   m_igaptime = 100;


   m_btrue_ly = true;

#ifdef CXVISIONDOG
	CDog::resolveDogLibrary();
#endif

	{ 
#ifdef TEMPTESTCXVISION
		m_ilogin = 1;	
		ShowLog(0,"License Find"); 
		ClientTextEdit->setEnabled(false); 
		if(NULL==m_imageViewer)
		{  
			m_imageViewer = new CxImageViewer(this);
			m_imageViewer->show();
			ShowLog(0,"ImageShow"); 
		}
		//if(CDog::DogLibraryisload())
		{
		 //	
		}
		//else
		{
			serverStart();
			clientStart();
			ServerstartButton->setEnabled(false);
			ClientstartButton->setEnabled(false);
			ServerTextEdit->setEnabled(true);//ServerTextEdit->setEnabled(false);

			ClientTextEdit->setEnabled(false); 
			CommandEdit->setEnabled(false);
			TimeTextEdit->setEnabled(false);
			adminiEdit->setEnabled(true);

			widgetList->setEnabled(false);
			widgetList2->setEnabled(false);

			quitButton->setEnabled(false); 

			adminiButton->setEnabled(false);
			compressButton->setEnabled(false);

			addDutyButton->setEnabled(false);
			MsgButton->setEnabled(false);
			SendFileButton->setEnabled(false);
			CommandButton->setEnabled(false); 
			this->hide();
		}
#else


#ifdef CXVISIONSERVERLICENSE
connect(&m_licstcpClient,
        &QAbstractSocket::connected,
         this,
        &Dialog::LSTransfer);
connect(&m_licstcpClient,
        &QIODevice::readyRead,
         this,
        &Dialog::LSReadyRead);
connect(&m_licstcpClient,
        QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
         this,
        &Dialog::LSError);



m_licstcpClient.connectToHost(QHostAddress::LocalHost, 60001);
#endif


#ifdef CXVISIONDOG
		if(CDog::DogLibraryisload())
#else
        if(0)//1client //0server
#endif
		{
			ShowLog(0,"Dog Load is OK");
            //cxtempa
            //clientStart();
            m_savefiledir = "";
            //serverStart();
            if(LicenseFind(3))
			{
				m_ilogin = 1;	
				ShowLog(0,"License Find"); 
				ClientTextEdit->setEnabled(false); 

#ifdef CXVISIONIMAGEVIEW
				if(NULL==m_imageViewer)
				{  
					m_imageViewer = new CxImageViewer(this);
					m_imageViewer->show();
					ShowLog(0,"ImageShow"); 
				}
				else
				{
					m_imageViewer->show();
					m_imageViewer->showNormal();
				}
#endif


				//sql
#ifdef CXVISIONBSERVER 	 
				if(NULL==m_sqlbrower)
				{
					m_sqlmain = new QMainWindow;
					m_sqlbrower = new SQLBrowser(m_sqlmain);
					SQLBrowser browser(m_sqlmain);
					m_sqlmain->setCentralWidget(m_sqlbrower);
                    QMenu *fileMenu = m_sqlmain->menuBar()->addMenu(QObject::tr("&File"));
                    fileMenu->addAction(QObject::tr("Add &Connection..."), m_sqlbrower, SLOT(addConnection()));
					fileMenu->addSeparator();
                    //fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit()));
                    //QMenu *helpMenu = m_sqlmain->menuBar()->addMenu(QObject::tr("&Help"));
                    //helpMenu->addAction(QObject::tr("About"), m_sqlbrower, SLOT(about()));
                    //helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt()));

                    QObject::connect(m_sqlbrower, SIGNAL(statusMessage(QString)),
						m_sqlmain->statusBar(), SLOT(showMessage(QString)));

					m_sqlmain->show();
					if (QSqlDatabase::connectionNames().isEmpty())
						QMetaObject::invokeMethod(m_sqlbrower, "addConnection", Qt::QueuedConnection);
					
				
					
				}
#endif
			}
			else 
			{
				m_ilogin = 0;
				ShowLog(0,"No DKey"); 
				
				ServerstartButton->setEnabled(false);
				ClientstartButton->setEnabled(false);
				ServerTextEdit->setEnabled(true);//ServerTextEdit->setEnabled(false);

				ClientTextEdit->setEnabled(false); 
				CommandEdit->setEnabled(false);
				TimeTextEdit->setEnabled(false);
				adminiEdit->setEnabled(true);

				widgetList->setEnabled(false);
				widgetList2->setEnabled(false);

				quitButton->setEnabled(false); 

				adminiButton->setEnabled(false);
				compressButton->setEnabled(false);

				addDutyButton->setEnabled(false);
				MsgButton->setEnabled(false);
				SendFileButton->setEnabled(false);
				CommandButton->setEnabled(false); 
				//////////////////////////////////////////////////////////////////////////
			}

            AddDutyfile();

        }
		else
		{

			ServerstartButton->setEnabled(false);
			ClientstartButton->setEnabled(false);
			ServerTextEdit->setEnabled(true);//ServerTextEdit->setEnabled(false);

            ClientTextEdit->setEnabled(true);
            CommandEdit->setEnabled(true);
            TimeTextEdit->setEnabled(true);
			adminiEdit->setEnabled(true);

            widgetList->setEnabled(true);
            widgetList2->setEnabled(true);

            quitButton->setEnabled(true);

            adminiButton->setEnabled(true);
            compressButton->setEnabled(true);

            addDutyButton->setEnabled(true);
            MsgButton->setEnabled(true);
            SendFileButton->setEnabled(true);
            CommandButton->setEnabled(true);
//			serverStart();
		}
#endif

        m_pdialogopt = 0;
        m_pdialogopt = m_pmanager->getopt();
        if(0!=m_pdialogopt)
            m_pdialogopt->setdialog(this);



        //m_ptestconsole = new Console;
        //m_pdownload = new DownloadManager(this);
        //m_pdownload = new DownloadManager(this);

        //if(0!=m_pdialogopt)
       //     this->ShowLog(0,"opt load ok");
       // m_pstringai = m_pmanager->getstringai();
       // if(0!=m_pstringai)
       //     this->ShowLog(0,"stringai load ok");

      //
        //m_pdialogopt->setdownload(m_pdownload);
        //m_pdialogopt->setconsole(m_pconsole);
        //load cxut

        m_editor->setText(m_pmanager->getloadcode());


    }
    ////////////////////////getlocationstringx//////////////////////


#ifdef CXVISIONPILLOW
     HTTPserverStart();
#else
#ifdef TEMPTESTCXVISION

	HTTPserverStart();
#endif

#endif

 //  m_localdutytimer.start(1000, this);
 //  m_connectsdutytimer.start(100, this);
 //  m_eventtimer.start(20,this);
   
 //  m_begintimes = 0;
 //  m_begintimer.start(1000,this);
 SetLoop(0,1);
 SetLoop(1,1);
 SetLoop(2,1);
 SetLoop(3,1);
 
#ifdef CXVISIONBSERVER
 m_hCxvisionMap = NULL;
 m_pcxvisionstruct = NULL;
 
GetCxVisionGolbalStruct();
#endif

m_idutynum = 0;
#ifdef CXPYTHON 
	m_pythontest = new CxPythonTest(this);
 	m_pythontest->PythontestRun();
#endif

	//////////////////////////////////////////////////////////////////////////
    showMaximized();
	//////////////////////////////////////////////////////////////////////////
    setWindowTitle(QString::fromLatin1("cxvisionaiv3-1.00ai"));



        m_itrigrun=-1;
        m_igetrun=-1;



        QString qnetserver = m_pmanager->GetParserString("netserver");

        if("false"!=qnetserver)
        {
            QString qnetport = m_pmanager->GetParserString("netport");
          if(qnetport!="")
              serverStart(qnetport.toInt());
          else
              serverStart(60000);
        }

        QString qcomslave = m_pmanager->GetParserString("comslave");

        if("true"==qcomslave)
        {
            QString portName = m_pmanager->GetParserString("portName");
            QString qwaitTimeout = m_pmanager->GetParserString("waitTimeout");

            startSlave(portName, qwaitTimeout.toInt());

        }
        QString qmodbustcp = m_pmanager->GetParserString("modbustcp");
        if("true"==qmodbustcp)
        {
            if(nullptr!=m_pdialogopt)
            {
                m_pdialogopt->modbustcp();
                m_pdialogopt->modbustcpconnect();
                m_pdialogopt->modbustcpsetinputimer(1,100);
                m_pdialogopt->modbustcpsetinputimer(2,100);
                m_pdialogopt->modbustcpsetinputimer(3,100);
            }

/*
opt.modbustcp();
opt.modbustcpconnect();

opt.modbustcpsetinputimer(1,300);
opt.modbustcpsetinputimer(2,300);
*/
        }
        QString qviewflash = m_pmanager->GetParserString("viewflash");
if("false"==qviewflash)
{
    m_pmanager->setflash(false);

}

  //  serverStart();
    //clientStart();
    //RunThread *thread = new RunThread(this);
  //connect(thread, SIGNAL(trig()), this, SLOT(TestParser()));
  //connect(thread, SIGNAL(trig()), this, SLOT(updateview()));
  //thread->start();
 m_lstimer.start(2500,this);
    m_ilockrun=0;
    m_ilasttrgnum=0;
    m_itrgnum=0;
    m_icurresult=-1;

/*QString qsfilename = tr("扫码异常");
    QString qsfilename = tr("\u626b\u7801\u5f02\u5e38");
    QString qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
    QByteArray qsend=qsend1.toUtf8();//toLatin1();
    setWindowTitle(qsend);
    ShowLog(0,qsend);
*/


}
void Dialog::LSTransfer()
{
    // called when the TCP client connected to the loopback server

}
void Dialog::LSReadyRead()
{
  // m_licstcpClient.write(QByteArray(qMin(bytesToWrite, PayloadSize), '@'));
  //m_licstcpClient.write(QByteArray(1, '@'));
  //   QByteArray qreadall = m_licstcpClient.readAll();
  //   if(qreadall.mid(0,1)!="@")
  //   {
  //       close();
  //   }
 }

void Dialog::LSError(QAbstractSocket::SocketError socketError)
{
    this->close();
    if (socketError == QTcpSocket::RemoteHostClosedError)
        return;

    QMessageBox::warning(this, tr("License Error"),tr("error"));
//                             tr("The following error occurred: %1.")
//                             .arg(m_licstcpClient.errorString()));


}




void Dialog::findCodecs()
{
    QMap<QString, QTextCodec *> codecMap;
    QRegularExpression iso8859RegExp("^ISO[- ]8859-([0-9]+).*$");
    QRegularExpressionMatch match;

    const QList<int> mibs = QTextCodec::availableMibs();
    for (int mib : mibs) {
        QTextCodec *codec = QTextCodec::codecForMib(mib);

        QString sortKey = codec->name().toUpper();
        int rank;

        if (sortKey.startsWith(QLatin1String("UTF-8"))) {
            rank = 1;
        } else if (sortKey.startsWith(QLatin1String("UTF-16"))) {
            rank = 2;
        } else if ((match = iso8859RegExp.match(sortKey)).hasMatch()) {
            if (match.captured(1).size() == 1)
                rank = 3;
            else
                rank = 4;
        } else {
            rank = 5;
        }
        sortKey.prepend(QLatin1Char('0' + rank));

        codecMap.insert(sortKey, codec);
    }
  //  codecs = codecMap.values();
}




void Dialog::ReSetLayout()
{
    if(true==m_btrue_ly)
    {
        m_btrue_ly=false;
        parserlayoutbox->removeWidget(TestParserButton);
        parserlayoutbox->removeWidget(SaveParserButton);
        m_blayout->removeWidget(buttonBox);
        m_blayout->removeWidget(CommandEdit);

        m_blayout->removeWidget(ServerTextEdit);
        m_blayout->removeWidget(serverStatusLabel);
        m_blayout->removeWidget(m_editor);

        m_blayout->removeWidget(clientProgressBar);
        m_blayout->removeWidget(clientStatusLabel);
        m_blayout->removeWidget(ClientTextEdit);
        TestParserButton->hide();
        SaveParserButton->hide();
        buttonBox->hide();
        CommandEdit->hide();
        ServerTextEdit->hide();
        serverStatusLabel->hide();
        m_editor->hide();
        clientProgressBar->hide();
        clientStatusLabel->hide();
        ClientTextEdit->hide();

    }
    else
    {
        m_btrue_ly=true;

        TestParserButton->show();
        SaveParserButton->show();
        buttonBox->show();
        CommandEdit->show();
        ServerTextEdit->show();
        serverStatusLabel->show();
        m_editor->show();
        clientProgressBar->show();
        clientStatusLabel->show();
        ClientTextEdit->show();
        parserlayoutbox->addWidget(TestParserButton);
        parserlayoutbox->addWidget(SaveParserButton);

            m_blayout->addWidget(buttonBox);
            m_blayout->addWidget(CommandEdit);

            m_blayout->addWidget(ServerTextEdit);
            m_blayout->addWidget(serverStatusLabel);
            m_blayout->addWidget(m_editor);

            m_blayout->addWidget(clientProgressBar);
            m_blayout->addWidget(clientStatusLabel);
            m_blayout->addWidget(ClientTextEdit);

    }
}
Dialog::~Dialog()
{

    QString qcstring ="drunRL=0;";
    m_pmanager->runstringcode(qcstring.toStdString().c_str());
    m_pmanager->saveautocreate();

    if(nullptr!=m_pmanager)
        delete m_pmanager;
    if(nullptr!=m_imageViewer)
		delete m_imageViewer;
    m_imageViewer = nullptr;
    if(nullptr!=m_sqlmain)
		delete m_sqlmain;
    m_sqlmain = nullptr;
    if(nullptr!=m_sqlbrower)
		delete m_sqlbrower;
    m_sqlbrower = nullptr;
	
#ifdef CXPYTHON 
	if(NULL!=m_pythontest)
		delete m_pythontest;
#endif

}




void Dialog::RunPyton(QString qcomm)
{
#ifdef CXPYTHON 
if(NULL!=m_pythontest)
	m_pythontest->PytonRunOne(qcomm);
#endif
}

 
#define   CXVISION_GOBAL_NAME  "Global\\REFIENR_{2B9DB0F0-BBDB-458e-904A-D063DFC5F777}" 
#define   SHARE_RESULT1FILE_NAME "Global\\REFIENR_{B520E159-9B22-4454-8672-442AF95446BD}"

//#define   CXVISION_STRUCT_NAME "Global\\REFIENR_{17A50421-DEB1-4375-9274-661FE35B3049}" 
#ifdef CXVISIONBSERVER
void Dialog::GetCxVisionGolbalStruct()
{
	SECURITY_ATTRIBUTES   ScrtyAttr   =   {0};
	ScrtyAttr.bInheritHandle   =   FALSE;   
	ScrtyAttr.lpSecurityDescriptor   =   NULL;   
	ScrtyAttr.nLength   =   sizeof(SECURITY_ATTRIBUTES);   
	//////////////////////////////////////////////////////////////////////////
	//cam map image buf
	m_hCxvisionMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS,
		FALSE,   
		CXVISION_GOBAL_NAME);  
	if(NULL!=m_hCxvisionMap)
	{ 
		m_pcxvisionstruct = (char*)MapViewOfFile(m_hCxvisionMap,
			FILE_MAP_ALL_ACCESS,
			0,0, 0);
		//memcpy(&m_runpro,m_pcxvisionstruct,sizeof(cxstruct));
	}
	else
	{
		m_hCxvisionMap   =   CreateFileMappingA(INVALID_HANDLE_VALUE,
			&ScrtyAttr,
			PAGE_READWRITE,     
			0,
			256,
			CXVISION_GOBAL_NAME);
		m_pcxvisionstruct = (char*)MapViewOfFile(m_hCxvisionMap,
			FILE_MAP_ALL_ACCESS,
			0,0, 0);
	}
	
	/////////////////////////////////////////
	//result cam file
	m_hResultfile1Map = OpenFileMappingA(FILE_MAP_ALL_ACCESS,
		FALSE,   
		SHARE_RESULT1FILE_NAME);  
	if(NULL!=m_hResultfile1Map)
	{ 
		m_pResultfileBuf1 = (char*)MapViewOfFile(m_hResultfile1Map,
			FILE_MAP_ALL_ACCESS,
			0,0, 0);
		//memcpy(&m_runpro,m_pcxvisionstruct,sizeof(cxstruct));
	}
	else
	{
		m_hResultfile1Map   =   CreateFileMappingA(INVALID_HANDLE_VALUE,
			&ScrtyAttr,
			PAGE_READWRITE,     
			0,
			256,
			SHARE_RESULT1FILE_NAME);
		m_pResultfileBuf1 = (char*)MapViewOfFile(m_hResultfile1Map,
			FILE_MAP_ALL_ACCESS,
			0,0, 0);
	}
	
 

} 
int Dialog::CurAppGolbalSet()
{

	if(NULL!=m_hCxvisionMap&&
		NULL!=m_pcxvisionstruct)
	{ 
		int isize = sizeof(cxstruct);
		char *pstren = new char[isize];
		memcpy(pstren,m_pcxvisionstruct,isize);

		CxConnection::Decrypt_(pstren,isize);

		cxstruct *pstruct = (cxstruct*)pstren;
		if(pstruct->m_iapphearton[3]>=0)
			pstruct->m_iapphearton[3] = pstruct->m_iapphearton[3]  + 1;
		if(pstruct->m_iapphearton[2]>=0)
			pstruct->m_iapphearton[2] = pstruct->m_iapphearton[2]  + 1;

		QString csTitle;
		csTitle = tr("CxVision Browser: %1").arg(pstruct->m_iapphearton[3]);
		setWindowTitle(csTitle);
		int igetnum = pstruct->m_iapphearton[3];

		CxConnection::Encrypt_(pstren,isize);

		memcpy(m_pcxvisionstruct,pstren,isize); 

		delete []pstren;

		return igetnum;
	}
	return -1;
}
void Dialog::CurAppGolbalReset()
{

	if(NULL!=m_hCxvisionMap&&
		NULL!=m_pcxvisionstruct)
	{
		//cxstruct *pstruct = (cxstruct*)m_pcxvisionstruct;
		//pstruct->m_iapphearton[0] = -1000 ;
		//pstruct->m_iapphearton[1] = -1000 ;
		//pstruct->m_iapphearton[2] = -1000 ;
		//pstruct->m_iapphearton[3] = -1000 ;

		//QString csTitle;
		//csTitle = tr("CxVision Browser: %1").arg(pstruct->m_iapphearton[3]);
		//setWindowTitle(csTitle);

//////////////////////////////////////////////////////////////////////////
		int isize = sizeof(cxstruct);
		char *pstren = new char[isize];
		memcpy(pstren,m_pcxvisionstruct,isize);

		CxConnection::Decrypt_(pstren,isize);

		cxstruct *pstruct = (cxstruct*)pstren;
		pstruct->m_iapphearton[0] = -1000 ;
		pstruct->m_iapphearton[1] = -1000 ;
		pstruct->m_iapphearton[2] = -1000 ;
		pstruct->m_iapphearton[3] = -1000 ;

		QString csTitle;
		csTitle = tr("CxVision Browser: %1").arg(pstruct->m_iapphearton[3]);
		setWindowTitle(csTitle);
		int igetnum = pstruct->m_iapphearton[3];

		CxConnection::Encrypt_(pstren,isize);

		memcpy(m_pcxvisionstruct,pstren,isize); 

		delete []pstren;

 

//////////////////////////////////////////////////////////////////////////


	}

}
void Dialog::CurAppGolbalUpData()
{

	if(NULL!=m_hCxvisionMap&&
		NULL!=m_pcxvisionstruct)
	{
		//cxstruct *pstruct = (cxstruct*)m_pcxvisionstruct;
		//pstruct->m_iapphearton[0] = -9999 ;
		//pstruct->m_iapphearton[1] = -9999 ;
		//pstruct->m_iapphearton[2] = -9999 ;
		//pstruct->m_iapphearton[3] = -9999 ; 

		//QString csTitle;
		//csTitle = tr("CxVision Browser: %1").arg(pstruct->m_iapphearton[3]);
		//setWindowTitle(csTitle);
		int isize = sizeof(cxstruct);
		char *pstren = new char[isize];
		memcpy(pstren,m_pcxvisionstruct,isize);

		CxConnection::Decrypt_(pstren,isize);

		cxstruct *pstruct = (cxstruct*)pstren;
		pstruct->m_iapphearton[0] = -9999 ;
		pstruct->m_iapphearton[1] = -9999 ;
		pstruct->m_iapphearton[2] = -9999 ;
		pstruct->m_iapphearton[3] = -9999 ;

		QString csTitle;
		csTitle = tr("CxVision Browser: %1").arg(pstruct->m_iapphearton[3]);
		setWindowTitle(csTitle);
		int igetnum = pstruct->m_iapphearton[3];

		CxConnection::Encrypt_(pstren,isize);

		memcpy(m_pcxvisionstruct,pstren,isize); 

		delete []pstren;
	}

}
#endif

void Dialog::newsql()
{
#ifdef CXVISIONBSERVER 
	ClientTextEdit->setEnabled(true); 
	CommandEdit->setEnabled(true);
	TimeTextEdit->setEnabled(true);
	adminiEdit->setEnabled(true);
	if(NULL==m_sqlbrower)
	{ 
		m_sqlmain = new QMainWindow;
		m_sqlbrower = new SQLBrowser(m_sqlmain);

		SQLBrowser browser(m_sqlmain);
		m_sqlmain->setCentralWidget(m_sqlbrower);

        QMenu *fileMenu = m_sqlmain->menuBar()->addMenu(QObject::tr("&File"));
        fileMenu->addAction(QObject::tr("Add &Connection..."), m_sqlbrower, SLOT(addConnection()));
		fileMenu->addSeparator();
        //fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit()));

        //QMenu *helpMenu = m_sqlmain->menuBar()->addMenu(QObject::tr("&Help"));
        //helpMenu->addAction(QObject::tr("About"), m_sqlbrower, SLOT(about()));
        //helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt()));

        QObject::connect(m_sqlbrower, SIGNAL(statusMessage(QString)),
			m_sqlmain->statusBar(), SLOT(showMessage(QString)));

		m_sqlmain->show();
		if (QSqlDatabase::connectionNames().isEmpty())
			QMetaObject::invokeMethod(m_sqlbrower, "addConnection", Qt::QueuedConnection);

	}
#endif
}
QString Dialog::GetInputText()
{
	return adminiEdit->text();
}
bool Dialog::islibload()
{
#ifdef CXVISIONDOG
	return CDog::DogLibraryisload();
#endif
}
bool Dialog::LicenseFind(int ifeature)
{

#ifdef CXVISION_TEST
		return TRUE;
#endif

#ifdef CXVISIONDOG
	const char* defaultScope = "<dogscope />";
	dogStatus status;
	CDogFeature feature = CDogFeature::fromFeature(ifeature);
	CDog dog(feature);
	status = dog.login(G_vendorCode, defaultScope);
	if (!DOG_SUCCEEDED(status))
	{ 
		status = dog.logout();
		return FALSE;
	} 
	status = dog.logout();
#endif
    return true;
}
void Dialog::HTTPserverStart()
{  
#ifdef CXVISIONPILLOW
//ssl load

    QFile certificateFile(":/cxvisionai-cert-768.pem");
    if (!certificateFile.open(QIODevice::ReadOnly))
    {
        //qDebug() << "Could not open certificate file '.crt'";
        //exit(2);

        ShowLog(0,"[HttpLOG:]Could not open key file '.crt'");
        return;
    }
    QSslCertificate certificate(&certificateFile);

    QFile keyFile(":/cxvisionai-key-768.pem");
    if (!keyFile.open(QIODevice::ReadOnly))
    {
       // qDebug() << "Could not open key file '.key'";
       // exit(3);

        ShowLog(0,"[HttpLOG:]Could not open key file '.key'");
        return;
    }
    QSslKey key(&keyFile, QSsl::Rsa);

   // HttpsServer server(certificate, key, QHostAddress(QHostAddress::Any), 4567);
   // if (!server.isListening()) exit(1);
   // qDebug() << "Ready";

//ssl load end
    //

    //m_httpserver =new Pillow::HttpsServer(certificate, key,QHostAddress(QHostAddress::Any), 81);


    //if (!m_httpserver->isListening())
    //{
    //    ShowLog(0,"[HttpLOG:]0.0.0.0:80 for listening: The bound address is already");
     //   return;
    //}
    //QScriptEngine*
    //m_scriptEngine = new QScriptEngine((QObject* )m_httpserver);

    //m_handler = new Pillow::HttpHandlerStack((QObject* )m_httpserver);
    //m_loghandler = new Pillow::HttpHandlerLog(m_handler);
    //new HttpHandlerQtScriptFile(scriptEngine, "test.js", "handleRequest", true, handler);

    //m_loghandler->setdialog(this);
 
    //m_statshandler = new  HttpHandlerStats(m_handler,this);
    //m_filehandler = new  HttpHandlerFile(getlocationstringx("./file"), m_handler);
   // m_404handler = new HttpHandler404(m_handler);//,this);

    //QObject::connect((QObject*) m_httpserver, SIGNAL(requestReady(Pillow::HttpConnection*)),
    //	m_handler, SLOT(handleRequest(Pillow::HttpConnection*)));

    //ShowLog(0,"[HttpLOG:]Ready");
    //QObject::connect((QObject*)m_loghandler, SIGNAL(HttpHandlerLog::logreq(const QString&)),
	//	this, SLOT(LogShow(const QString&)));
	
#endif
 
}
void Dialog::HTTPserverStop()
{   
#ifdef CXVISIONPILLOW
	if(m_404handler)
	delete m_404handler;
	if(m_filehandler)
	delete m_filehandler;
	if(m_statshandler)
	delete m_statshandler;
	if(m_handler)
	delete m_handler;
	if(m_httpserver)
	delete m_httpserver ;

  
	ShowLog(0,"[HttpLOG:]Close"); 
	m_404handler = NULL;
	m_filehandler = NULL;
	m_statshandler = NULL;
	m_handler = NULL;
	m_httpserver  = NULL;
#endif
}

void Dialog::sethttpreqstring(const QByteArray &pagestr)
{
		m_httpsendbuf = pagestr;
	//if(m_brq)
	//m_rq->writeResponseString(200, HttpHeaderCollection(), qlog);
}
void Dialog::GetHttpFile(const QByteArray& filecontents)
{
	//-----------------------------7db37aa1701e8
	//	Content-Disposition: form-data; name="newfile"; filename="ntimage.gif"
	//	Content-Type: image/gif 
	//  Content-Disposition: form-data; name="newfile"; filename="arduino epprom.txt"
	//	Content-Type: text/plain
	//setContent(
	//Content-Type
	
	
	//QByteArray abytearray = "Content-Type";
	//int ipos = filecontents.indexOf(abytearray);
	//QByteArray abyteget = filecontents.mid(ipos+abytearray.size()+1);
	//QByteArray abytearray = "";

#ifdef CXVISIONBSERVER	
    BrowserWindow*pview = NULL;
	pview = m_pageviewlist[0];
	pview->SetFrameViewContent(filecontents);
#endif
    BrowserWindow*pview = NULL;

	//ShowHttpLog(tr("cxtest %1 ").arg(ipos)+abyteget);
	//QByteArray dataf;
 
}
QByteArray Dialog::gethttpreqstring()
{

	return m_httpsendbuf;//QByteArray(".............................");
}

#ifdef CXVISIONPILLOW
HttpHeaderCollection Dialog::gethttphead()
{
	return m_httpsendhead;//QByteArray(".............................");
}
#endif
bool Dialog::sethttplog(const QByteArray &qlog )
{

#ifdef CXVISIONPILLOW
	QByteArray result = qlog;
	m_httpsendbuf.clear(); 

	if(result.mid(0,6)=="/page?")
	{
		sethttpreqtype(1);
		QByteArray qbary = result.mid(6);
		ShowHttpLog("[Run:Page]"+qbary);
		m_reqarray = qbary;
		AddLoacalDuty(m_reqarray,1,tr("20"));
 
		m_httpsendbuf = m_reqarray;
		
		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		
		return true;
	}
	if(result.mid(0,8)=="/google?")
	{
		sethttpreqtype(1);
		QByteArray qbary = result.mid(8);
		ShowHttpLog("[Run:]"+qbary);
		m_reqarray = qbary;
		AddLoacalDuty(tr("https://www.google.com.hk/search?q=")+m_reqarray,1,tr("20"));

		m_httpsendbuf = tr("https://www.google.com.hk/search?q=").toLocal8Bit()+m_reqarray;

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		
		return true;
	}
	if(result.mid(0,8)=="/bing?")
	{
		sethttpreqtype(1);
		QByteArray qbary = result.mid(8);
		ShowHttpLog("[Run:]"+qbary);
		m_reqarray = qbary;
		AddLoacalDuty(tr("https://www.bing.com/search?q=")+m_reqarray,1,tr("20"));

		m_httpsendbuf = tr("https://www.bing.com/search?q=").toLocal8Bit()+m_reqarray;
		

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		return true;
	}
	else if(result.mid(0,6)=="/file?")
	{
		sethttpreqtype(1);
		QByteArray qbary = result.mid(6);
		ShowHttpLog("[Run:]"+qbary);
		m_reqarray = qbary;
		AddLoacalDuty(m_reqarray,2,tr("20"));
 
		m_httpsendbuf = m_reqarray;
		

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		
		return true;
	}
	//else if(result.mid(0,6)=="/image?")
	//{
	//	sethttpreqtype(2);
	//	QByteArray qbary = result.mid(7);
	//	ShowHttpLog("[Run:]"+qbary);
	//	m_reqarray = qbary; 
	//	AddLoacalDuty(m_reqarray,3,tr("20"));
    //
	//	m_httpsendbuf = m_reqarray;
    //
	//	m_httpsendhead.clear();
	//	m_httpsendhead.reserve(2);
	//	m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
	//	QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
	//	QByteArray etag = md5sum.result().toHex();
	//	m_httpsendhead << HttpHeader("ETag", etag);
    //
	//	return true;
	//}
	else if(result.mid(0,8)=="/search?")
	{
		sethttpreqtype(1);
		QByteArray qbary = result.mid(8);

		ShowHttpLog("[Run:]"+qbary);
		m_reqarray = qbary;
		WGetPage(0,tr("https://www.google.com.hk/search?q=")+m_reqarray);
		m_httpsendbuf = tr("https://www.google.com.hk/search?q=").toLocal8Bit()+m_reqarray;
		

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		
		return true;
 
	}
	else if(result.mid(0,9)=="/content?")
	{
#ifdef CXVISIONPILLOW
		sethttpreqtype(3);
		QByteArray qbary = result.mid(9);
		if(m_pageviewlist[0])
		{
			 
			ShowHttpLog("[Run:]"+qbary);
#ifdef CXVISIONSERVER
            QByteArray content = m_pageviewlist[0]->GetFramePageHtml().toLocal8Bit();
            m_httpsendbuf = content;
#else
            m_httpsendbuf = QByteArray("NO USE");
#endif

			

			m_httpsendhead.clear();
			m_httpsendhead.reserve(2);
			m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"

            QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);

            QByteArray etag = md5sum.result().toHex();
			m_httpsendhead << HttpHeader("ETag", etag);
		}
#endif
		return true;
	}
	else if(result.mid(0,5)=="/all?")
	{
		sethttpreqtype(3); 
		QString qstrall ;

#ifdef CXVISIONDOG
        if(CDog::DogLibraryisload())
#else
        if(1)
#endif
		{ 

			if(LicenseFind(3))
			{
				for(int i=0;i<m_textlist.size();i++)
				{
					qstrall = qstrall + m_textlist[i]+tr("\r\n");
				}
				ShowHttpLog("[Run:All]");
			}
		}
		else
		{
			qstrall = "!!not cxvision admin ip and key";
		} 
        m_httpsendbuf = qstrall.toLocal8Bit();//.toAscii();

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		
		return true;
	}	
	else if(result.mid(0,5)=="/run:")
	{
		sethttpreqtype(3); 


				//%
				QByteArray qbary = result.mid(5);
                QByteArray qbary1 = qbary.replace("|"," ");
				//%20
				ShowHttpLog("[Run:]"+qbary1);
				m_reqarray = qbary1;
				CommandEdit->setText(qbary1);  
                sendCommand();
                ShowHttpLog(tr("RUN:")+qbary1);



         m_httpsendbuf = qbary1;//.toAscii();
		

		m_httpsendhead.clear();
		m_httpsendhead.reserve(2);
		m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
		QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
		QByteArray etag = md5sum.result().toHex();
		m_httpsendhead << HttpHeader("ETag", etag);
		return true;
	} 
    else if(result.mid(0,10)=="/download?")
    {
        sethttpreqtype(1);
        QByteArray qbary = result.mid(12);
        qbary = qbary.left(qbary.size()-12);

        ShowHttpLog("[download link:]"+qbary);
        m_reqarray = qbary;
        //AddLoacalDuty(tr("https://www.google.com.hk/search?q=")+m_reqarray,1);
        //%3A->:
        //%2F->/
        QString qstr = m_reqarray;        qstr.replace("%3A",":");
        qstr.replace("%2F","/");
        //%22->"
        qstr.replace("%22","\"");
        //%3B->;
        qstr.replace("%3B",";");
        //"%5C->\"
        qstr.replace("%5C","\\");
        //%2B->+
        qstr.replace("%2B","+");

        //-->-
        //*->*
        //%28->(
        qstr.replace("%28","(");

        //%29->)
        qstr.replace("%29",")");

        //%7B->{
        qstr.replace("%7B","{");

        //%7D->}
        qstr.replace("%7D","}");

        //%7E->~
        qstr.replace("%7E","~");

        //%40->@
        qstr.replace("%40","@");

        //%23->#
        qstr.replace("%23","#");

        //%3D->=
        qstr.replace("%3D","=");



        ShowHttpLog("[download link:]"+qstr);

        QString qstrdown = tr("opt.tcp2tcpstring(\"opt.download(\\\"") + qstr + tr("\\\");\");");

        AddTFileDuty(qstrdown);
//        m_editor->setText(qstrdown);
//        m_pmanager->runstringcode(m_editor->text().toStdString().c_str());

        m_httpsendbuf = tr(" download link :").toLocal8Bit()+qstr.toLocal8Bit();

        m_httpsendhead.clear();
        m_httpsendhead.reserve(2);
        m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
        QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
        QByteArray etag = md5sum.result().toHex();
        m_httpsendhead << HttpHeader("ETag", etag);

        return true;
    }
    else if(result.mid(0,5)=="/run?")
    {
        sethttpreqtype(1);
        QByteArray qbary = result.mid(12);
        qbary = qbary.left(qbary.size()-12);

        ShowHttpLog("[download link:]"+qbary);
        m_reqarray = qbary;
        //AddLoacalDuty(tr("https://www.google.com.hk/search?q=")+m_reqarray,1);
        //%3A->:
        //%2F->/
        QString qstr = m_reqarray;        qstr.replace("%3A",":");
        qstr.replace("%2F","/");
        //%22->"
        qstr.replace("%22","\"");
        //%3B->;
        qstr.replace("%3B",";");
        //"%5C->\"
        qstr.replace("%5C","\\");
        //%2B->+
        qstr.replace("%2B","+");

        //-->-
        //*->*
        //%28->(
        qstr.replace("%28","(");

        //%29->)
        qstr.replace("%29",")");

        //%7B->{
        qstr.replace("%7B","{");

        //%7D->}
        qstr.replace("%7D","}");

        //%7E->~
        qstr.replace("%7E","~");

        //%40->@
        qstr.replace("%40","@");

        //%23->#
        qstr.replace("%23","#");

        //%3D->=
        qstr.replace("%3D","=");



        ShowHttpLog("[run:]"+qstr);


            SetCommandEditText(qstr);
            sendCommand();


        m_httpsendbuf = tr(" run :").toLocal8Bit()+qstr.toLocal8Bit();

        m_httpsendhead.clear();
        m_httpsendhead.reserve(2);
        m_httpsendhead << HttpHeader("Content-Type", "text/html");
        QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
        QByteArray etag = md5sum.result().toHex();
        m_httpsendhead << HttpHeader("ETag", etag);

        return true;
    }
    else if(result.mid(0,9)=="/compile?")
    {
        sethttpreqtype(1);
        QByteArray qbary = result.mid(8);
        qbary = qbary.left(qbary.size()-12);

        ShowHttpLog("[compile:]"+qbary);
        m_reqarray = qbary;
        //AddLoacalDuty(tr("https://www.google.com.hk/search?q=")+m_reqarray,1);
        //%3A->:
        //%2F->/
        QString qstr = m_reqarray;
        {
        qstr.replace("%3A",":");
        qstr.replace("%2F","/");
        //%22->"
        qstr.replace("%22","\"");
        //%3B->;
        qstr.replace("%3B",";");
        //"%5C->\"
        qstr.replace("%5C","\\");
        //%2B->+
        qstr.replace("%2B","+");
        //-->-
        //*->*
        //%28->(
        qstr.replace("%28","(");

        //%29->)
        qstr.replace("%29",")");

        //%7B->{
        qstr.replace("%7B","{");

        //%7D->}
        qstr.replace("%7D","}");

        //%7E->~
        qstr.replace("%7E","~");

        //%40->@
        qstr.replace("%40","@");

        //%23->#
        qstr.replace("%23","#");

        //%3D->=
        qstr.replace("%3D","=");
        }
        //%3D->=
        qstr.replace("|"," ");

        ShowHttpLog("[compile:]"+qstr);

        QString qstrdown =  qstr  ;

        m_editor->setText(qstrdown);

        m_pmanager->runstringcode(m_editor->toPlainText().toStdString().c_str());

        m_httpsendbuf = tr(" compile :").toLocal8Bit()+qstr.toLocal8Bit()+ m_pmanager->getoutputstring().toLocal8Bit();

        m_httpsendhead.clear();
        m_httpsendhead.reserve(2);
        m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
        QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
        QByteArray etag = md5sum.result().toHex();
        m_httpsendhead << HttpHeader("ETag", etag);

        return true;
    }
    else if(result.mid(0,10)=="/image.jpg")
	{
		 sethttpreqtype(2);
		//	QByteArray qbary = result.mid(7);  
        m_image = QPixmap::grabWindow(QApplication::desktop()->winId()).toImage();
        QString imgFormat(QLatin1String("image/jpg"));
        QByteArray f(imgFormat.mid(6).toUtf8());//.toAscii();
		m_httpsendbuf.clear();
		QBuffer w(&m_httpsendbuf);
		w.open(QIODevice::WriteOnly);
		QImageWriter writer(&w, f.toUpper());
		if (writer.write(m_image))
		{
			w.close(); 
 
			m_httpsendhead.clear();
			m_httpsendhead.reserve(2);
            m_httpsendhead << HttpHeader("Content-Type", "image/jpeg");//��ʾͼ��ʹ�� "image/jpeg"
			QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
			QByteArray etag = md5sum.result().toHex();
			m_httpsendhead << HttpHeader("ETag", etag); 
		 } 
		//////////////////////////////////////////////////////////////////////////
		return true;
	} 
	else if(result.mid(0,5)=="/view")
	{
		sethttpreqtype(2);
	//	int iviewnum = result.at(5).toInt();
        BrowserWindow*pview = NULL;
		pview = m_pageviewlist[0];
		if(result.mid(0,6)=="/view0")
		{
			pview = m_pageviewlist[0];
		}
		else if(result.mid(0,6)=="/view1")
		{
			if(m_pageviewlist.size()>1)
				pview = m_pageviewlist[1];
		}
		else if(result.mid(0,6)=="/view2")
		{
			if(m_pageviewlist.size()>2)
				pview = m_pageviewlist[2];			
		}
		else if(result.mid(0,6)=="/view3")
		{ 
			if(m_pageviewlist.size()>3)
				pview = m_pageviewlist[3];					
		}  
		

		if(pview==NULL)	
			return true;

#ifdef CXVISIONBSERVER  
		int iw,ih;
		m_image  = pview->GetFrameQImage(iw,ih);// QPixmap::grabWidget(pview,pview->frameGeometry()).toImage();
		 
        //m_image = QScreen::grabWindow(QApplication::desktop()->winId()).toImage();
		QString imgFormat(QLatin1String("image/PNG"));
		QByteArray f(imgFormat.mid(6).toAscii());
		m_httpsendbuf.clear();
		QBuffer w(&m_httpsendbuf);
		w.open(QIODevice::WriteOnly);
		QImageWriter writer(&w, f.toUpper());
		if (writer.write(m_image))
		{
			w.close(); 

			m_httpsendhead.clear();
			m_httpsendhead.reserve(2);
			m_httpsendhead << HttpHeader("Content-Type", "image/png");//��ʾͼ��ʹ�� "image/jpeg"
			QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
			QByteArray etag = md5sum.result().toHex();
			m_httpsendhead << HttpHeader("ETag", etag); 
		} 
#endif
		//////////////////////////////////////////////////////////////////////////
		return true;
	} 
	else if(result.mid(0,7)=="/dialog")
	{
		sethttpreqtype(2);
		//QByteArray qbary = result.mid(7);  
        //m_image = QScreen::grabWindow(QApplication::desktop()->winId()).toImage();
        m_image  = QPixmap::grabWidget(this,this->frameGeometry()).toImage();
		QString imgFormat(QLatin1String("image/PNG"));
        QByteArray f(imgFormat.mid(6).toUtf8());//.toAscii();
		m_httpsendbuf.clear();
		QBuffer w(&m_httpsendbuf);
		w.open(QIODevice::WriteOnly);
		QImageWriter writer(&w, f.toUpper());
		if (writer.write(m_image))
		{
			w.close(); 

			m_httpsendhead.clear();
			m_httpsendhead.reserve(2);
			m_httpsendhead << HttpHeader("Content-Type", "image/png");//��ʾͼ��ʹ�� "image/jpeg"
			QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
			QByteArray etag = md5sum.result().toHex();
			m_httpsendhead << HttpHeader("ETag", etag); 
		} 
 		return true;
	} 
	else if(result.mid(0,8)=="/camdemo")
	{ 
		sethttpreqtype(3); 
		QString qstrall ;
		
		//CxConnection * pconnect = GetActiveConnect();
		//if(NULL!=pconnect)
		//	AddDuty_front(pconnect,tr("getdesktop"));

		//
#ifdef CXVISIONDOG
		if(CDog::DogLibraryisload())
		{ 
			if(LicenseFind(3))
			{
				qstrall = "find key and login ";

			}
		}
#endif
        m_httpsendbuf = qstrall.toUtf8();//.toAscii();toAscii();
		return true;
	}
	else if(result.mid(0,6)=="/host")
	{
		sethttpreqtype(2);
		//QByteArray qbary = result.mid(7);  
		//m_image = QPixmap::grabWindow(QApplication::desktop()->winId()).toImage();
		QString imgFormat(QLatin1String("image/PNG"));
        QByteArray f(imgFormat.mid(6).toUtf8());//.toAscii();
		m_httpsendbuf.clear();
		QBuffer w(&m_httpsendbuf);
		w.open(QIODevice::WriteOnly);
		QImageWriter writer(&w, f.toUpper());
		if (writer.write(m_image))
		{
			w.close();   
			m_httpsendhead.clear();
			m_httpsendhead.reserve(2);
			m_httpsendhead << HttpHeader("Content-Type", "image/jpeg");//��ʾͼ��ʹ�� "image/jpeg"
			QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
			QByteArray etag = md5sum.result().toHex();
			m_httpsendhead << HttpHeader("ETag", etag); 
		}  
		return true;
	} 
	else if(result.mid(0,10)=="/login?")
	{ 
		sethttpreqtype(3); 
		QString qstrall ;
#ifdef CXVISIONDOG
		if(CDog::DogLibraryisload())
		{ 
			if(LicenseFind(3))
			{
				qstrall = "find key and login ";
			
			}
		}
#endif

        m_httpsendbuf = qstrall.toUtf8();//.toAscii();
		return true;
	}
    else if(result.mid(0,6)=="/files")
    {
        QByteArray qbary = result.mid(5);
        m_httpsendbuf = qbary;

        m_httpsendhead.clear();
        m_httpsendhead.reserve(2);
        m_httpsendhead << HttpHeader("Content-Type", "text/html");//��ʾͼ��ʹ�� "image/jpeg"
        QCryptographicHash md5sum(QCryptographicHash::Md5); md5sum.addData(m_httpsendbuf);
        QByteArray etag = md5sum.result().toHex();
        m_httpsendhead << HttpHeader("ETag", etag);

    }
#endif
	return false; 
	
}

void Dialog::serverStart(int netport)
{
    //m_ics = 0;//server
    ServerstartButton->setEnabled(false);
    ClientstartButton->setEnabled(false);
    //addDutyButton->setEnabled(false);
    connect(&tcpServer, SIGNAL(newConnection()),this, SLOT(ServeracceptConnection()));

#ifndef QT_NO_CURSOR
//    QApplication::setOverrideCursor(Qt::WaitCursor);
#endif

    bytesWritten = 0;
    bytesReceived = 0;

    while (!tcpServer.isListening() && !tcpServer.listen(QHostAddress::Any,netport))
    {
        QMessageBox::StandardButton ret = QMessageBox::critical(this,
                                        tr("CxServer"),
                                        tr("Unable to start the test: %1.")
                    .arg(tcpServer.errorString()),
                                        QMessageBox::Retry
                    | QMessageBox::Cancel);
        if (ret == QMessageBox::Cancel)
            return;
    }
    ShowLog(0,tr("Server Start,port 60000"));
    serverStatusLabel->setText(tr("Listening"));

//	setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8"));

}
void Dialog::restartserver()
{
#ifndef QT_NO_CURSOR
//	QApplication::setOverrideCursor(Qt::WaitCursor);
#endif 
	tcpServer.close();

	connect(&tcpServer, SIGNAL(newConnection()),this, SLOT(ServeracceptConnection()));

	connect(&tcpServer, SIGNAL(newConnection()),this, SLOT(NewConnections()));

	bytesWritten = 0;
	bytesReceived = 0;
	QString serverport = adminiEdit->text();
	int iport = 82;
	if(serverport!="")
		iport = serverport.toInt(); 
	while (!tcpServer.isListening() && !tcpServer.listen(QHostAddress::Any,iport)) 
	{ 
		reconnectTimer.start();
	}

	serverStatusLabel->setText(tr("Listening"));
}
void Dialog::restartruntimer()
{
	reconnectTimer.start();
}
void Dialog::restartclient( )
{	
	reconnectTimer.stop();

	ServerstartButton->setEnabled(false);

	ClientstartButton->setEnabled(false);

//cxf	if(1==m_ics)//client 
	{
#ifdef CXVISIONDOG
		if(CDog::DogLibraryisload())
#else
        if(1)
#endif
        {
			m_ptcpClient = new QTcpSocket;
			connect(m_ptcpClient, SIGNAL(connected()),this, SLOT(ClientIsConnection()));
			QHostAddress qaddress;

			m_serverip = adminiEdit->text();
			m_serverport = tr("82") ;
			QStringList	alistparm  = m_serverip.split(QLatin1String(":"));
			if(alistparm.size()>=2)
			{
				m_serverip = alistparm.at(0);
				m_serverport = alistparm.at(1);
			}	

			if(m_serverip=="")
			{

                qaddress.setAddress(QLatin1String("192.168.1.2"));//192.168.1.2"));
                m_serverip = QLatin1String("192.168.1.2");//192.168.1.2");
            //	qaddress.setAddress(QLatin1String("192.168.1.2"));
            //	m_serverip = QLatin1String("192.168.1.2");
				m_serverport = tr("82");
            //	ShowLog(0,tr("connectaddress:192.168.1.2:82"));
                ShowLog(0,tr("connectaddress:192.168.1.2:82"));
			}
			else 
			{
				qaddress.setAddress(m_serverip);
				ShowLog(0,tr("connectaddress:")+m_serverip+tr(":")+m_serverport);
			}

			CxConnection *pconnect = GetActiveConnect();
			if(NULL==pconnect)  
				SetActiveConnect(pconnect);
			if(pconnect)
				pconnect->reconnect(m_ptcpClient,0);

			if(m_serverport!="")
				pconnect->connectToHost(qaddress,m_serverport.toInt());
			else
				pconnect->connectToHost(qaddress,82);


			const int Timeout = 10 * 1000;

			if (!m_ptcpClient->waitForConnected(Timeout)) 
			{
				pconnect->overconnect();

				ClientstartButton->setEnabled(true);
				clientStatusLabel->setText(tr("No Connected"));
				ShowLog(0,tr("retry No Connected"));
				reconnectTimer.start();
				return;
			}
			else
				pconnect->connectisok();
		}
	} 
	//ClienttransferButton->setEnabled(false);

    //setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8"));
}

void Dialog::clientStart()
{
    newconnect_project();
}

void Dialog::LoginUSER(CxConnection*pconnect)
{
	QString qstuser = pconnect->GetUser();

	CxConnectS aconnect;
	aconnect.m_pconnect = pconnect;
	aconnect.m_qsuser = qstuser;
	m_connections.push_back(aconnect);
	
	ReFlashUSER();


}
void Dialog::ReFlashUSER()
{
	widgetList2->clear();
	
	for(int i=0;i<m_connections.size();i++)
	{  
		CxConnection*pconnect = m_connections[i].m_pconnect;

		QString qstuser = pconnect->GetUser();
		
		//if(1==m_ics)//client //cxf
        if(0==pconnect->IScors())//client
            widgetList2->addItem(pconnect->getio_local_address_string()
                                 +tr(":%1").arg(pconnect->iolocalport())
                                 +tr(" ")+qstuser);
		else if(1==pconnect->IScors())//server
            widgetList2->addItem(pconnect->getio_local_address_string()
                                 +tr(":%1").arg(pconnect->iopeerport())
                                 +tr(" ")+qstuser);
	} 

	for(int i=0;i<m_P2Pconnections.size();i++)
	{  
		CxConnection*pconnect = m_P2Pconnections[i].m_pconnect;

		QString qstuser = pconnect->GetUser();

		if(0==pconnect->IScors())//client
            widgetList2->addItem(tr("[P2P]")+pconnect->getio_local_address_string()
                                 +tr(":%1").arg(pconnect->iopeerport())
                                 +tr(" ")+qstuser);
		else if(1==pconnect->IScors())
            widgetList2->addItem(tr("[P2P]")+pconnect->getio_peer_address_string()
                                 +tr(":%1").arg(pconnect->iopeerport())
                                 +tr(" ")+qstuser);

	} 

}
CxConnection*Dialog::GetConnect(int inum)
{
	for(int i=0;i<m_connections.size();i++)
	{  
		if(inum == i)
			return m_connections[i].m_pconnect;
	}
}

void Dialog::ServeracceptConnection()
{
    tcpServerConnection = tcpServer.nextPendingConnection();
    if (!tcpServerConnection) {
        serverStatusLabel->setText(tr("Error: got invalid pending connection!"));
        return;
    }

    connect(tcpServerConnection, &QIODevice::readyRead,
            this, &Dialog::ServerReadyRead_project_yangquan);//ServerReadyRead_project_yongkang);//ServerReadyRead_project_biwo);//ServerReadyRead);

    connect(tcpServerConnection, &QTcpSocket::disconnected,
            tcpServerConnection, &QTcpSocket::deleteLater);

    serverStatusLabel->setText(tr("Accepted connection"));

    quint16 iport2 =  tcpServerConnection ->peerPort();
    QHostAddress hostadress2 =  tcpServerConnection ->peerAddress();
    QString hostname =  tcpServerConnection ->peerName();

    QString cxtest =QString(tr("Accepted connection: ")) + hostadress2.toString() + QString(tr(" Port: %1").arg(iport2));

    ShowLog(nullptr,cxtest);
    //!!!cxvision tcpServer.close();

    /*
    tcpServerConnection  = tcpServer.nextPendingConnection();
	
	CxConnection *pconnection = new CxConnection(tcpServerConnection,this,1);//server 1

	CxConnection *pconnect = GetActiveConnect();
    if(NULL==pconnect)
		SetActiveConnect(pconnect);

	 pconnection->connectisok();

	quint16 iport2 =  tcpServerConnection ->peerPort();
	QHostAddress hostadress2 =  tcpServerConnection ->peerAddress();
	QString hostname =  tcpServerConnection ->peerName();
	
	QString cxtest =QString(tr("Accepted connection: ")) + hostadress2.toString() + QString(tr(" Port: %1").arg(iport2));

	serverStatusLabel->setText(cxtest);

	ShowLog(0,cxtest); 
    */
}
void Dialog::ServerReadyRead()
{
    bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();

    QString qtrgnum=QString(qreadall);
    int itrgnum = qtrgnum.toInt();
    m_pmanager->SetParserValue(QString("trignum"),itrgnum);
    ShowLog(0,qtrgnum);

   double dvalue = m_pmanager->GetParserValue(QString("result"));
   //ShowLog(0,tr("%1").arg(dvalue));
   //if(itrgnum>0)
   {
      int iresult= dvalue;
      QByteArray qsend = QString(tr("%1").arg(iresult)).toLatin1();
      tcpServerConnection->write(qsend);
      //m_pmanager->runstringcodex(m_editor->toPlainText().toStdString().c_str());
        runopt("main");
   }
}


void Dialog::mkdir(const QString &astr)
{
    const QDir cxDir(astr);
    if (!cxDir.exists())
    {
       if (!cxDir.mkpath(astr))
       {
          return ;
       }
    }
}

WorkerThread::WorkerThread():QThread()
{
}
void WorkerThread::setrun(Dialog*pdlg,int itrg)
{
    m_dlg=pdlg;
    m_itrgnum=itrg;
}
void WorkerThread::run()
{
        m_dlg->runparser(m_itrgnum);
}


void Dialog::runparser(int itrgnum)
{

    if(1==itrgnum)
    {
        m_iruntimetrg=0;

        runopt("1");
        m_iruntimeok=1;
    }
    else if(2==itrgnum)
    {
        m_iruntimetrg=0;

        runopt("2");
        m_iruntimeok=1;
    }
    else if(3==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("3");
        m_iruntimeok=1;
    }
    else if(4==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("4");
        m_iruntimeok=1;
    }
    else if(5==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("5");
        m_iruntimeok=1;
    }
    else if(6==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("6");
        m_iruntimeok=1;
    }
    else if(7==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("7");
        m_iruntimeok=1;
    }
    else if(8==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("8");
        m_iruntimeok=1;
    }
    else if(9==m_iruntimetrg)
    {
        m_iruntimetrg=0;
        runopt("9");
        m_iruntimeok=1;
    }


}

void Dialog::ServerReadyRead_project()
{
    //   tcpServerConnection->setSocketOption LowDelayOption
   // bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();
//peek
    QString qtrgnum=QString(qreadall);
    //ShowLog(nullptr,qtrgnum);

    //ShowLog(0,qtrgnum.mid(0,7));
    if(qtrgnum.mid(0,7)==QString("CCD:GAP"))
    {
        QByteArray qsend = QString(tr("CCD:GO")).toLatin1();
        tcpServerConnection->write(qsend);
        int iGAP = qtrgnum.mid(7).toInt();
        m_pmanager->SetParserValue(QString("onegap"),iGAP);

        ShowLog(nullptr,QString("S:CCD:P1")+qtrgnum.mid(7));
    }
    else if(qtrgnum.mid(0,5)==QString("CCD:P"))
    {
        int itrgnum = qtrgnum.mid(5).toInt();

        m_ilasttrgnum=m_itrgnum;
        m_itrgnum=itrgnum;

        if(m_ilockrun>0)
         {
             ShowLog(nullptr,QString("lockrun return"));
         }
        if(m_ilockrun<1)
        {
                m_ilockrun = 1;
                QString qtrig = qtrgnum.mid(5,1);

                QTime time;
                time.restart();
                int ielapsetime=0;
                int ilimittime=700;
                QString qstrp;
                if(2==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=2;
                    m_pmanager->SetParserValue(QString("drunRL"),2);
                     runopt("2t");
                      qstrp =  QString(tr("\\P2"));

                }
                else if(3==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=3;
                    m_pmanager->SetParserValue(QString("drunRL"),3);
                    runopt("3t");
                    qstrp =  QString(tr("\\P3"));
                }
                else if(4==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=4;
                    m_pmanager->SetParserValue(QString("drunRL"),4);
                    runopt("4t");
                    qstrp =  QString(tr("\\P4"));
                }
                else if(5==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=5;
                    m_pmanager->SetParserValue(QString("drunRL"),5);
                    runopt("5t");
                    qstrp =  QString(tr("\\P5"));
                }
                else if(6==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=6;
                    m_pmanager->SetParserValue(QString("drunRL"),6);
                    runopt("6t");
                    qstrp =  QString(tr("\\P6"));
                }
                else if(7==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=7;
                    m_pmanager->SetParserValue(QString("drunRL"),7);
                    runopt("7t");
                    qstrp =  QString(tr("\\P7"));
                }
                else if(8==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=8;
                    m_pmanager->SetParserValue(QString("drunRL"),8);
                    runopt("8t");
                    qstrp =  QString(tr("\\P8"));
                }
                else if(9==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=9;
                    m_pmanager->SetParserValue(QString("drunRL"),9);
                    runopt("9t");
                    qstrp =  QString(tr("\\P9"));
                }

                 WorkerThread m_workerThread;
                if(m_iruntimetrg>0)
                {
                   ////////////////////////////////
                   m_workerThread.setrun(this,itrgnum);
                   m_workerThread.start(QThread::HighestPriority);
                    while (ielapsetime < ilimittime
                           && m_iruntimeok< 1)
                    {
                        ielapsetime=time.elapsed();
                    }
                    ///////////////////////////////
                }
                double dvalue = 0;
                int iresult= 0;
                if(itrgnum>0)
                {
                   if(m_iruntimeok>0)
                   {
                       ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = m_pmanager->GetParserValue(QString("result"));
                   }
                   else
                   {
                       ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = 4;
                   }
                   iresult= dvalue;
                   QString qresult = QString("O");
                   if(0==iresult)
                   {
                       qresult = QString("O");//E1/2/3
                       m_icurresult=iresult;
                   }
                   else if(1==iresult)
                   {
                       qresult = QString("E1");//E1/2/3
                   }
                   else if(2==iresult)
                   {
                       qresult = QString("E2");//E1/2/3
                   }
                   else if(3==iresult)
                   {
                       qresult = QString("E3");//E1/2/3
                   }
                   else if(4==iresult)
                   {
                       qresult = QString("E4");//run overtime
                   }
                   m_ilockrun = 0;
                   QByteArray qsend = (QString(tr("CCD:P%1").arg(itrgnum))+qresult).toLatin1();
                   tcpServerConnection->write(qsend);
                   ShowLog(nullptr,QString("S:")+qsend);
                   double ds = m_pmanager->GetParserValue(QString("ds"));

                   if(ds>2)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }
                   else if(ds>1&&iresult>0)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }

                }

                m_workerThread.quit();
                m_workerThread.wait();

        }
    }
    else if(qtrgnum.mid(0,10)==QString("CCD:TrayId"))
    {
        QString qcoderesult = m_pmanager->getcodeparserstring();
        QString qresult=QString("CCD:T")+qcoderesult;
        QByteArray qsend =qresult.toLatin1();
        tcpServerConnection->write(qsend);
        ShowLog(0,QString("S:")+qresult);
    }
    else if(qtrgnum.mid(0,8)==QString("CCD:Data"))
    {
        QString qstationnum = qtrgnum.mid(9);
        int itrigstation = qstationnum.toInt();
        m_pmanager->SetParserValue(QString("dstationnum"),itrigstation);
        ShowLog(0,QString("Get:Station %1").arg(itrigstation));
        QString qtrig = qtrgnum.mid(8,1);
        if(qtrig==QString("R"))
            runopt("DataR");
        else if(qtrig==QString("L"))
            runopt("DataL");

        double dx1,dy1,dr1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));

        double dx2,dy2,dr2;
        dx2 = m_pmanager->GetParserValue(QString("dx2"));
        dy2 = m_pmanager->GetParserValue(QString("dy2"));
        dr2 = m_pmanager->GetParserValue(QString("dr2"));
        double dx3,dy3,dr3;
        dx3 = m_pmanager->GetParserValue(QString("dx3"));
        dy3 = m_pmanager->GetParserValue(QString("dy3"));
        dr3 = m_pmanager->GetParserValue(QString("dr3"));
        double dx4,dy4,dr4;
        dx4 = m_pmanager->GetParserValue(QString("dx4"));
        dy4 = m_pmanager->GetParserValue(QString("dy4"));
        dr4 = m_pmanager->GetParserValue(QString("dr4"));
        double dx5,dy5,dr5;
        dx5 = m_pmanager->GetParserValue(QString("dx5"));
        dy5 = m_pmanager->GetParserValue(QString("dy5"));
        dr5 = m_pmanager->GetParserValue(QString("dr5"));
        double dx6,dy6,dr6;
        dx6 = m_pmanager->GetParserValue(QString("dx6"));
        dy6 = m_pmanager->GetParserValue(QString("dy6"));
        dr6 = m_pmanager->GetParserValue(QString("dr6"));
        double dx7,dy7,dr7;
        dx7 = m_pmanager->GetParserValue(QString("dx7"));
        dy7 = m_pmanager->GetParserValue(QString("dy7"));
        dr7 = m_pmanager->GetParserValue(QString("dr7"));
        double dallvalue;
        dallvalue = m_pmanager->GetParserValue(QString("allresult"));
        QString qerrormsg;

        QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        QString qsend1;
        QString qsfilename = tr("坐标异常");
        if(dallvalue<1)
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
        else
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+QString(tr("\",\"Layer_Pos\":["));

        QString qsend2 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3},").arg(dr1, 0, 'f').arg(dx1, 0, 'f').arg(dy1, 0, 'f'));
        QString qsend3 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3},").arg(dr2, 0, 'f').arg(dx2, 0, 'f').arg(dy2, 0, 'f'));
        QString qsend4 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3},").arg(dr3, 0, 'f').arg(dx3, 0, 'f').arg(dy3, 0, 'f'));
        QString qsend5 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3},").arg(dr4, 0, 'f').arg(dx4, 0, 'f').arg(dy4, 0, 'f'));
        QString qsend6 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3},").arg(dr5, 0, 'f').arg(dx5, 0, 'f').arg(dy5, 0, 'f'));
        QString qsend7 = QString(tr("{\"R\":%1,\"X\":%2,\"Y\":%3}").arg(dr6, 0, 'f').arg(dx6, 0, 'f').arg(dy6, 0, 'f'));
        QString qsend8 = QString(tr("],\"Result\":%1,\"Tray_ID\":\"%2\",").arg(dallvalue).arg(qcoderesult));
        QString qsend9 = QString(tr("\"Tray_Pos\":{\"R\":%1,\"X\":%2,\"Y\":%3}}").arg(dr7, 0, 'f').arg(dx7, 0, 'f').arg(dy7, 0, 'f'));
        QString qsendx = qsend1 + qsend2 + qsend3 + qsend4 + qsend5 + qsend6 + qsend7+ qsend8+ qsend9;
        qsend = qsendx.toLocal8Bit();
        tcpServerConnection->write(qsend);
        ShowLog(nullptr,QString("S:")+qsend);
    }

}

void Dialog::ServerReadyRead_projectv2()
{
    //   tcpServerConnection->setSocketOption LowDelayOption
   // bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();
//peek
    QString qtrgnum=QString(qreadall);
    ShowLog(nullptr,qtrgnum);

    //ShowLog(0,qtrgnum.mid(0,7));
    if(qtrgnum.mid(0,7)==QString("CCD:GAP"))
    {
        QByteArray qsend = QString(tr("CCD:GO")).toLatin1();
        tcpServerConnection->write(qsend);
        int iGAP = qtrgnum.mid(7).toInt();
        m_pmanager->SetParserValue(QString("onegap"),iGAP);

        ShowLog(nullptr,QString("S:CCD:P1")+qtrgnum.mid(7));
    }
    else if(qtrgnum.mid(0,5)==QString("CCD:P"))
    {
        int itrgnum = qtrgnum.mid(5).toInt();

        m_ilasttrgnum=m_itrgnum;
        m_itrgnum=itrgnum;

        if(m_ilockrun>0)
         {
             ShowLog(nullptr,QString("lockrun return"));m_ilockrun = 0;return;//3.17
         }
        if(m_ilockrun<1)
        {
                m_ilockrun = 1;
                QString qtrig = qtrgnum.mid(5,1);

                QTime time;
                time.restart();
                int ielapsetime=0;
                int ilimittime=800;
                QString qstrp;

                if(1==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=1;
                    m_pmanager->SetParserValue(QString("drunRL"),1);
                     runopt("1t");
                      qstrp =  QString(tr("\\P1"));

                }
                else if(2==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=2;
                    m_pmanager->SetParserValue(QString("drunRL"),2);
                     runopt("2t");
                      qstrp =  QString(tr("\\P2"));

                }
                else if(3==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=3;
                    m_pmanager->SetParserValue(QString("drunRL"),3);
                    runopt("3t");
                    qstrp =  QString(tr("\\P3"));
                }
                else if(4==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=4;
                    m_pmanager->SetParserValue(QString("drunRL"),4);
                    runopt("4t");
                    qstrp =  QString(tr("\\P4"));
                }
                else if(5==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=5;
                    m_pmanager->SetParserValue(QString("drunRL"),5);
                    runopt("5t");
                    qstrp =  QString(tr("\\P5"));
                }
                else if(6==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=6;
                    m_pmanager->SetParserValue(QString("drunRL"),6);
                    runopt("6t");
                    qstrp =  QString(tr("\\P6"));
                }
                else if(7==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=7;
                    m_pmanager->SetParserValue(QString("drunRL"),7);
                    runopt("7t");
                    qstrp =  QString(tr("\\P7"));
                }
                else if(8==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=8;
                    m_pmanager->SetParserValue(QString("drunRL"),8);
                    runopt("8t");
                    qstrp =  QString(tr("\\P8"));
                }
                else if(9==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=9;
                    m_pmanager->SetParserValue(QString("drunRL"),9);
                    runopt("9t");
                    qstrp =  QString(tr("\\P9"));
                }

                 WorkerThread m_workerThread;
                if(m_iruntimetrg>0)
                {
                   ////////////////////////////////
                   m_workerThread.setrun(this,itrgnum);
                   m_workerThread.start(QThread::HighestPriority);
                    while (ielapsetime < ilimittime
                           && m_iruntimeok< 1)
                    {
                        ielapsetime=time.elapsed();
                    }
                    ///////////////////////////////
                }
                double dvalue = 0;
                int iresult= 0;
                if(itrgnum>0)
                {
                   if(m_iruntimeok>0)
                   {
                       ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = m_pmanager->GetParserValue(QString("result"));
                   }
                   else
                   {
                       ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = 4;
                   }
                   iresult= dvalue;
                   QString qresult = QString("O");
                   if(0==iresult)
                   {
                       qresult = QString("O");//E1/2/3
                       m_icurresult=iresult;
                   }
                   else if(1==iresult)
                   {
                       qresult = QString("E1");//E1/2/3
                   }
                   else if(2==iresult)
                   {
                       qresult = QString("E2");//E1/2/3
                   }
                   else if(3==iresult)
                   {
                       qresult = QString("E3");//E1/2/3
                   }
                   else if(4==iresult)
                   {
                       qresult = QString("E4");//run overtime
                   }
                   m_ilockrun = 0;
                   QByteArray qsend = (QString(tr("CCD:P%1").arg(itrgnum))+qresult).toLatin1();
                   tcpServerConnection->write(qsend);
                   ShowLog(nullptr,QString("S:")+qsend);
                   double ds = m_pmanager->GetParserValue(QString("ds"));

                   if(ds>2)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }
                   else if(ds>1&&iresult>0)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }

                }

                m_workerThread.quit();
                m_workerThread.wait();

        }
    }
    else if(qtrgnum.mid(0,10)==QString("CCD:TrayId"))
    {
        QString qcoderesult = m_pmanager->getcodeparserstring();
        QString qresult=QString("CCD:T")+qcoderesult;
        QByteArray qsend =qresult.toLatin1();
        tcpServerConnection->write(qsend);
        ShowLog(0,QString("S:")+qresult);
    }
    else if(qtrgnum.mid(0,8)==QString("CCD:Data"))
    {
        QString qstationnum = qtrgnum.mid(9);
        int itrigstation = qstationnum.toInt();
        m_pmanager->SetParserValue(QString("dstationnum"),itrigstation);
        ShowLog(0,QString("Get:Station %1").arg(itrigstation));
        QString qtrig = qtrgnum.mid(8,1);
        if(qtrig==QString("R"))
            runopt("DataR");
        else if(qtrig==QString("L"))
            runopt("DataL");
        else
            runopt("Data");

        double dx1,dy1,dr1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));

        double dx2,dy2,dr2;
        dx2 = m_pmanager->GetParserValue(QString("dx2"));
        dy2 = m_pmanager->GetParserValue(QString("dy2"));
        dr2 = m_pmanager->GetParserValue(QString("dr2"));
        double dx3,dy3,dr3;
        dx3 = m_pmanager->GetParserValue(QString("dx3"));
        dy3 = m_pmanager->GetParserValue(QString("dy3"));
        dr3 = m_pmanager->GetParserValue(QString("dr3"));

        double dx7,dy7,dr7;
        dx7 = m_pmanager->GetParserValue(QString("dx7"));
        dy7 = m_pmanager->GetParserValue(QString("dy7"));
        dr7 = m_pmanager->GetParserValue(QString("dr7"));
        double dallvalue;
        dallvalue = m_pmanager->GetParserValue(QString("allresult"));
        QString qerrormsg;

        QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        QString qsend1;
        QString qsfilename = tr("坐标异常");
        if(dallvalue<1)
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
        else
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+QString(tr("\",\"Layer_Pos\":["));

        QString qsend2 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr1, 0, 'f').arg(dx1, 0, 'f').arg(dy1, 0, 'f'));
        QString qsend3 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr2, 0, 'f').arg(dx2, 0, 'f').arg(dy2, 0, 'f'));
        QString qsend4 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3}").arg(dr3, 0, 'f').arg(dx3, 0, 'f').arg(dy3, 0, 'f'));
        QString qsend8 = QString(tr("],\"Result\":%1,\"Tray_ID\":\"%2\",").arg(dallvalue).arg(qcoderesult));
        QString qsend9 = QString(tr("\"Tray_Pos\":{\"R\":%1,\"X\":%2,\"Y\":%3}}").arg(dr7, 0, 'f').arg(dx7, 0, 'f').arg(dy7, 0, 'f'));
        QString qsendx = qsend1 + qsend2 + qsend3 + qsend4 + qsend8+ qsend9;
        qsend = qsendx.toLocal8Bit();
        tcpServerConnection->write(qsend);
        ShowLog(nullptr,QString("S:")+qsend);
    }



}

void Dialog::AutoSaveImage(QString &qsavedir)
{

    double ds = m_pmanager->GetParserValue(QString("ds"));

    if(ds>2)
    {
        QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
        if(pimage)
        {
            QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
            mkdir(QString(tr("D:\\ORG\\")));
            QDateTime now = QDateTime::currentDateTime();
            QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
            QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
            mkdir(qstrdate);
            mkdir(qstrdate+QString(tr("\\"))+qsavedir);
            QString qsavefile = qstrdate+QString(tr("\\"))+qsavedir+QString(tr("\\"))+qstrtimes+QString(".jpg");
            pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
        }
    }
}
void Dialog::ServerReadyRead_project_yangquan()
{
    //   tcpServerConnection->setSocketOption LowDelayOption
   // bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();
//peek
    QString qtrgnum=QString(qreadall);
    ShowLog(nullptr,qtrgnum);

    //ShowLog(0,qtrgnum.mid(0,7));
    if(qtrgnum.mid(0,7)==QString("CCD:GAP"))
    {
        QByteArray qsend = QString(tr("CCD:GO")).toLatin1();
        tcpServerConnection->write(qsend);
        int iGAP = qtrgnum.mid(7).toInt();
        m_pmanager->SetParserValue(QString("onegap"),iGAP);

        ShowLog(nullptr,QString("S:CCD:P1")+qtrgnum.mid(7));
    }
    else if(qtrgnum.mid(0,5)==QString("CCD:P"))
    {
        int itrgnum = qtrgnum.mid(5).toInt();

        m_ilasttrgnum=m_itrgnum;
        m_itrgnum=itrgnum;

        if(m_ilockrun>0)
         {
             ShowLog(nullptr,QString("lockrun return"));
             m_ilockrun = 0;
             return;//3.17
         }
        if(m_ilockrun<1)
        {
                m_ilockrun = 1;
                QString qtrig = qtrgnum.mid(5,1);

                QTime time;
                time.restart();
                int ielapsetime=0;
                int ilimittime=800;
                QString qstrp;

                if(1==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=1;
                    m_pmanager->SetParserValue(QString("drunRL"),1);
                     runopt("1t");
                      qstrp =  QString(tr("\\P1"));

                }
                else if(2==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=2;
                    m_pmanager->SetParserValue(QString("drunRL"),2);
                     runopt("2t");
                      qstrp =  QString(tr("\\P2"));

                }
                else if(3==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=3;
                    m_pmanager->SetParserValue(QString("drunRL"),3);
                    runopt("3t");
                    qstrp =  QString(tr("\\P3"));
                }
                else if(4==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=4;
                    m_pmanager->SetParserValue(QString("drunRL"),4);
                    runopt("4t");
                    qstrp =  QString(tr("\\P4"));
                }
                else if(5==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=5;
                    m_pmanager->SetParserValue(QString("drunRL"),5);
                    runopt("5t");
                    qstrp =  QString(tr("\\P5"));
                }
                else if(6==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=6;
                    m_pmanager->SetParserValue(QString("drunRL"),6);
                    runopt("6t");
                    qstrp =  QString(tr("\\P6"));
                }
                else if(7==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=7;
                    m_pmanager->SetParserValue(QString("drunRL"),7);
                    runopt("7t");
                    qstrp =  QString(tr("\\P7"));
                }
                else if(8==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=8;
                    m_pmanager->SetParserValue(QString("drunRL"),8);
                    runopt("8t");
                    qstrp =  QString(tr("\\P8"));
                }
                else if(9==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=9;
                    m_pmanager->SetParserValue(QString("drunRL"),9);
                    runopt("9t");
                    qstrp =  QString(tr("\\P9"));
                }

                runparser(itrgnum);
                ShowLog(nullptr,QString("run:")+m_pmanager->getoutputstring());
                m_pmanager->clearos();
                ielapsetime=time.elapsed();
                double dvalue = 0;
                int iresult= 0;
                if(itrgnum>0)
                {
                   if(ilimittime>ielapsetime)
                   {
                       ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = m_pmanager->GetParserValue(QString("result"));
                   }
                   else
                   {
                       ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = 4;
                   }
                   iresult= dvalue;
                   QString qresult = QString("O");
                   if(0==iresult)
                   {
                       qresult = QString("O");//E1/2/3
                       m_icurresult=iresult;
                   }
                   else if(1==iresult)
                   {
                       qresult = QString("E1");//E1/2/3
                   }
                   else if(2==iresult)
                   {
                       qresult = QString("E2");//E1/2/3
                   }
                   else if(3==iresult)
                   {
                       qresult = QString("E3");//E1/2/3
                   }
                   else if(4==iresult)
                   {
                       qresult = QString("E4");//run overtime
                   }
                   m_ilockrun = 0;
                   QByteArray qsend = (QString(tr("CCD:P%1").arg(itrgnum))+qresult).toLatin1();
                   tcpServerConnection->write(qsend);
                   ShowLog(nullptr,QString("S:")+qsend);
                   double ds = m_pmanager->GetParserValue(QString("ds"));

                   if(ds>2)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }
                   else if(ds>1&&iresult>0)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }

                }


        }
    }
    else if(qtrgnum.mid(0,10)==QString("CCD:TrayId"))
    {
        QString qcoderesult = m_pmanager->getcodeparserstring();
        QString qresult=QString("CCD:T")+qcoderesult;
        QByteArray qsend =qresult.toLatin1();
        tcpServerConnection->write(qsend);
        ShowLog(0,QString("S:")+qresult);
    }
    else if(qtrgnum.mid(0,8)==QString("CCD:Data"))
    {
        QString qstationnum = qtrgnum.mid(9);
        int itrigstation = qstationnum.toInt();
        m_pmanager->SetParserValue(QString("dstationnum"),itrigstation);
        ShowLog(0,QString("Get:Station %1").arg(itrigstation));
        QString qtrig = qtrgnum.mid(8,1);
        if(qtrig==QString("R"))
            runopt("DataR");
        else if(qtrig==QString("L"))
            runopt("DataL");
        else
            runopt("Data");

        double dx1,dy1,dr1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));

        double dx2,dy2,dr2;
        dx2 = m_pmanager->GetParserValue(QString("dx2"));
        dy2 = m_pmanager->GetParserValue(QString("dy2"));
        dr2 = m_pmanager->GetParserValue(QString("dr2"));
        double dx3,dy3,dr3;
        dx3 = m_pmanager->GetParserValue(QString("dx3"));
        dy3 = m_pmanager->GetParserValue(QString("dy3"));
        dr3 = m_pmanager->GetParserValue(QString("dr3"));

        double dx7,dy7,dr7;
        dx7 = m_pmanager->GetParserValue(QString("dx7"));
        dy7 = m_pmanager->GetParserValue(QString("dy7"));
        dr7 = m_pmanager->GetParserValue(QString("dr7"));
        double dallvalue;
        dallvalue = m_pmanager->GetParserValue(QString("allresult"));
        QString qerrormsg;

        QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        QString qsend1;
        QString qsfilename = tr("坐标异常");
        if(dallvalue<1)
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
        else
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+QString(tr("\",\"Layer_Pos\":["));

        QString qsend2 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr1, 0, 'f').arg(dx1, 0, 'f').arg(dy1, 0, 'f'));
        QString qsend3 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr2, 0, 'f').arg(dx2, 0, 'f').arg(dy2, 0, 'f'));
        QString qsend4 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3}").arg(dr3, 0, 'f').arg(dx3, 0, 'f').arg(dy3, 0, 'f'));
        QString qsend8 = QString(tr("],\"Result\":%1,\"Tray_ID\":\"%2\",").arg(dallvalue).arg(qcoderesult));
        QString qsend9 = QString(tr("\"Tray_Pos\":{\"R\":%1,\"X\":%2,\"Y\":%3}}").arg(dr7, 0, 'f').arg(dx7, 0, 'f').arg(dy7, 0, 'f'));
        QString qsendx = qsend1 + qsend2 + qsend3 + qsend4 + qsend8+ qsend9;
        qsend = qsendx.toLocal8Bit();
        tcpServerConnection->write(qsend);
        ShowLog(nullptr,QString("S:")+qsend);
    }
    //test
    else if(qtrgnum.mid(0,2)==QString("kk"))
    {
       // QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        m_pmanager->SetParserValue(QString("drunRL"),1);
        runopt("1t");
        runopt("2t");
        runopt("1");
        double dx1,dy1,dr1,dz1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));
         dz1 = m_pmanager->GetParserValue(QString("dz1"));
      QString qsend1  = QString(tr("[%1,%2,%3,%4,0]").arg(dx1, 0, 'f',3).arg(dy1, 0, 'f',3).arg(dz1, 0, 'f',3).arg(dr1, 0, 'f',3));
      ShowLog(nullptr,qsend1);
      qsend = qsend1.toLocal8Bit();
      tcpServerConnection->write(qsend);

      mkdir(QString(tr("D:\\ORG\\")));
      QDateTime now = QDateTime::currentDateTime();
      QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
      QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
      mkdir(qstrdate);
      QImage *pimage = m_pmanager->GetParserImage(QString("aimage1"));
      QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
      if(pimage)
      {
          QString qsavefile = qstrdate+QString(tr("\\C1_"))+qstrtimes+QString(".jpg");
          pimage->save(qsavefile,"JPEG");
          ShowLog(0,QString("save:")+qsavefile);
      }
      pimage = m_pmanager->GetParserImage(QString("aimage2"));
      if(pimage)
      {
          QString qsavefile = qstrdate+QString(tr("\\C2_"))+qstrtimes+QString(".jpg");
          pimage->save(qsavefile,"JPEG");
          ShowLog(0,QString("save:")+qsavefile);
      }

    }


}
void Dialog::ServerReadyRead_project_yongkang()
{
    //   tcpServerConnection->setSocketOption LowDelayOption
   // bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();
//peek
    QString qtrgnum=QString(qreadall);
    ShowLog(nullptr,qtrgnum);

    //ShowLog(0,qtrgnum.mid(0,7));
    if(qtrgnum.mid(0,7)==QString("CCD:GAP"))
    {
        QByteArray qsend = QString(tr("CCD:GO")).toLatin1();
        tcpServerConnection->write(qsend);
        int iGAP = qtrgnum.mid(7).toInt();
        m_pmanager->SetParserValue(QString("onegap"),iGAP);

        ShowLog(nullptr,QString("S:CCD:P1")+qtrgnum.mid(7));
    }
    else if(qtrgnum.mid(0,5)==QString("CCD:P"))
    {
        int itrgnum = qtrgnum.mid(5).toInt();

        m_ilasttrgnum=m_itrgnum;
        m_itrgnum=itrgnum;

        if(m_ilockrun>0)
         {
             ShowLog(nullptr,QString("lockrun return"));
             m_ilockrun = 0;
             return;//3.17
         }
        if(m_ilockrun<1)
        {
                m_ilockrun = 1;
                QString qtrig = qtrgnum.mid(5,1);

                QTime time;
                time.restart();
                int ielapsetime=0;
                int ilimittime=800;
                QString qstrp;

                if(1==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=1;
                    m_pmanager->SetParserValue(QString("drunRL"),1);
                     runopt("1t");
                      qstrp =  QString(tr("\\P1"));

                }
                else if(2==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=2;
                    m_pmanager->SetParserValue(QString("drunRL"),2);
                     runopt("2t");
                      qstrp =  QString(tr("\\P2"));

                }
                else if(3==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=3;
                    m_pmanager->SetParserValue(QString("drunRL"),3);
                    runopt("3t");
                    qstrp =  QString(tr("\\P3"));
                }
                else if(4==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=4;
                    m_pmanager->SetParserValue(QString("drunRL"),4);
                    runopt("4t");
                    qstrp =  QString(tr("\\P4"));
                }
                else if(5==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=5;
                    m_pmanager->SetParserValue(QString("drunRL"),5);
                    runopt("5t");
                    qstrp =  QString(tr("\\P5"));
                }
                else if(6==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=6;
                    m_pmanager->SetParserValue(QString("drunRL"),6);
                    runopt("6t");
                    qstrp =  QString(tr("\\P6"));
                }
                else if(7==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=7;
                    m_pmanager->SetParserValue(QString("drunRL"),7);
                    runopt("7t");
                    qstrp =  QString(tr("\\P7"));
                }
                else if(8==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=8;
                    m_pmanager->SetParserValue(QString("drunRL"),8);
                    runopt("8t");
                    qstrp =  QString(tr("\\P8"));
                }
                else if(9==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=9;
                    m_pmanager->SetParserValue(QString("drunRL"),9);
                    runopt("9t");
                    qstrp =  QString(tr("\\P9"));
                }

                runparser(itrgnum);
                ShowLog(nullptr,QString("run:")+m_pmanager->getoutputstring());
                m_pmanager->clearos();
                ielapsetime=time.elapsed();
                double dvalue = 0;
                int iresult= 0;
                if(itrgnum>0)
                {
                   if(ilimittime>ielapsetime)
                   {
                       ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = m_pmanager->GetParserValue(QString("result"));
                   }
                   else
                   {
                       ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = 4;
                   }
                   iresult= dvalue;
                   QString qresult = QString("O");
                   if(0==iresult)
                   {
                       qresult = QString("O");//E1/2/3
                       m_icurresult=iresult;
                   }
                   else if(1==iresult)
                   {
                       qresult = QString("E1");//E1/2/3
                   }
                   else if(2==iresult)
                   {
                       qresult = QString("E2");//E1/2/3
                   }
                   else if(3==iresult)
                   {
                       qresult = QString("E3");//E1/2/3
                   }
                   else if(4==iresult)
                   {
                       qresult = QString("E4");//run overtime
                   }
                   m_ilockrun = 0;
                   QByteArray qsend = (QString(tr("CCD:P%1").arg(itrgnum))+qresult).toLatin1();
                   tcpServerConnection->write(qsend);
                   ShowLog(nullptr,QString("S:")+qsend);
                   double ds = m_pmanager->GetParserValue(QString("ds"));

                   if(ds>2)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }
                   else if(ds>1&&iresult>0)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }

                }


        }
    }
    else if(qtrgnum.mid(0,10)==QString("CCD:TrayId"))
    {
        QString qcoderesult = m_pmanager->getcodeparserstring();
        QString qresult=QString("CCD:T")+qcoderesult;
        QByteArray qsend =qresult.toLatin1();
        tcpServerConnection->write(qsend);
        ShowLog(0,QString("S:")+qresult);
    }
    else if(qtrgnum.mid(0,8)==QString("CCD:Data"))
    {
        QString qstationnum = qtrgnum.mid(9);
        int itrigstation = qstationnum.toInt();
        m_pmanager->SetParserValue(QString("dstationnum"),itrigstation);
        ShowLog(0,QString("Get:Station %1").arg(itrigstation));
        QString qtrig = qtrgnum.mid(8,1);
        if(qtrig==QString("R"))
            runopt("DataR");
        else if(qtrig==QString("L"))
            runopt("DataL");
        else
            runopt("Data");

        double dx1,dy1,dr1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));

        double dx2,dy2,dr2;
        dx2 = m_pmanager->GetParserValue(QString("dx2"));
        dy2 = m_pmanager->GetParserValue(QString("dy2"));
        dr2 = m_pmanager->GetParserValue(QString("dr2"));
        double dx3,dy3,dr3;
        dx3 = m_pmanager->GetParserValue(QString("dx3"));
        dy3 = m_pmanager->GetParserValue(QString("dy3"));
        dr3 = m_pmanager->GetParserValue(QString("dr3"));
        double dx4,dy4,dr4;
        dx4 = m_pmanager->GetParserValue(QString("dx4"));
        dy4 = m_pmanager->GetParserValue(QString("dy4"));
        dr4 = m_pmanager->GetParserValue(QString("dr4"));

        double dx7,dy7,dr7;
        dx7 = m_pmanager->GetParserValue(QString("dx7"));
        dy7 = m_pmanager->GetParserValue(QString("dy7"));
        dr7 = m_pmanager->GetParserValue(QString("dr7"));
        double dallvalue;
        dallvalue = m_pmanager->GetParserValue(QString("allresult"));
        QString qerrormsg;

        QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        QString qsend1;
        QString qsfilename = tr("坐标异常");
        if(dallvalue<1)
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
        else
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+QString(tr("\",\"Layer_Pos\":["));

        QString qsend2 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr1, 0, 'f').arg(dx1, 0, 'f').arg(dy1, 0, 'f'));
        QString qsend3 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr2, 0, 'f').arg(dx2, 0, 'f').arg(dy2, 0, 'f'));
        QString qsend4 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr3, 0, 'f').arg(dx3, 0, 'f').arg(dy3, 0, 'f'));
        QString qsend5 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3}").arg(dr4, 0, 'f').arg(dx4, 0, 'f').arg(dy4, 0, 'f'));
        QString qsend8 = QString(tr("],\"Result\":%1,\"Tray_ID\":\"%2\",").arg(dallvalue).arg(qcoderesult));
        QString qsend9 = QString(tr("\"Tray_Pos\":{\"R\":%1,\"X\":%2,\"Y\":%3}}").arg(dr7, 0, 'f').arg(dx7, 0, 'f').arg(dy7, 0, 'f'));
        QString qsendx = qsend1 + qsend2 + qsend3 + qsend4 + qsend5 + qsend8+ qsend9;
        qsend = qsendx.toLocal8Bit();
        tcpServerConnection->write(qsend);
        ShowLog(nullptr,QString("S:")+qsend);
    }



}
void Dialog::ServerReadyRead_project_biwo()
{
    //   tcpServerConnection->setSocketOption LowDelayOption
   // bytesReceived += int(tcpServerConnection->bytesAvailable());
    QByteArray qreadall = tcpServerConnection->readAll();
//peek
    QString qtrgnum=QString(qreadall);
    ShowLog(nullptr,qtrgnum);

    //ShowLog(0,qtrgnum.mid(0,7));
    if(qtrgnum.mid(0,7)==QString("CCD:GAP"))
    {
        QByteArray qsend = QString(tr("CCD:GO")).toLatin1();
        tcpServerConnection->write(qsend);
        int iGAP = qtrgnum.mid(7).toInt();
        m_pmanager->SetParserValue(QString("onegap"),iGAP);

        ShowLog(nullptr,QString("S:CCD:P1")+qtrgnum.mid(7));
    }
    else if(qtrgnum.mid(0,5)==QString("CCD:P"))
    {
        int itrgnum = qtrgnum.mid(5).toInt();

        m_ilasttrgnum=m_itrgnum;
        m_itrgnum=itrgnum;

        if(m_ilockrun>0)
         {
             ShowLog(nullptr,QString("lockrun return"));
             m_ilockrun = 0;
             return;//3.17
         }
        if(m_ilockrun<1)
        {
                m_ilockrun = 1;
                QString qtrig = qtrgnum.mid(5,1);

                QTime time;
                time.restart();
                int ielapsetime=0;
                int ilimittime=800;
                QString qstrp;

                if(1==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=1;
                    m_pmanager->SetParserValue(QString("drunRL"),1);
                     runopt("1t");
                      qstrp =  QString(tr("\\P1"));

                }
                else if(2==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=2;
                    m_pmanager->SetParserValue(QString("drunRL"),2);
                     runopt("2t");
                      qstrp =  QString(tr("\\P2"));

                }
                else if(3==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=3;
                    m_pmanager->SetParserValue(QString("drunRL"),3);
                    runopt("3t");
                    qstrp =  QString(tr("\\P3"));
                }
                else if(4==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=4;
                    m_pmanager->SetParserValue(QString("drunRL"),4);
                    runopt("4t");
                    qstrp =  QString(tr("\\P4"));
                }
                else if(5==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=5;
                    m_pmanager->SetParserValue(QString("drunRL"),5);
                    runopt("5t");
                    qstrp =  QString(tr("\\P5"));
                }
                else if(6==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=6;
                    m_pmanager->SetParserValue(QString("drunRL"),6);
                    runopt("6t");
                    qstrp =  QString(tr("\\P6"));
                }
                else if(7==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=7;
                    m_pmanager->SetParserValue(QString("drunRL"),7);
                    runopt("7t");
                    qstrp =  QString(tr("\\P7"));
                }
                else if(8==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=8;
                    m_pmanager->SetParserValue(QString("drunRL"),8);
                    runopt("8t");
                    qstrp =  QString(tr("\\P8"));
                }
                else if(9==itrgnum)
                {
                    m_iruntimeok=0;
                    m_iruntimetrg=9;
                    m_pmanager->SetParserValue(QString("drunRL"),9);
                    runopt("9t");
                    qstrp =  QString(tr("\\P9"));
                }

                runparser(itrgnum);
                ShowLog(nullptr,QString("run:")+m_pmanager->getoutputstring());
                m_pmanager->clearos();
                ielapsetime=time.elapsed();
                double dvalue = 0;
                int iresult= 0;
                if(itrgnum>0)
                {
                   if(ilimittime>ielapsetime)
                   {
                       ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = m_pmanager->GetParserValue(QString("result"));
                   }
                   else
                   {
                       ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime)+qtrig);
                       dvalue = 4;
                   }
                   iresult= dvalue;
                   QString qresult = QString("O");
                   if(0==iresult)
                   {
                       qresult = QString("O");//E1/2/3
                       m_icurresult=iresult;
                   }
                   else if(1==iresult)
                   {
                       qresult = QString("E1");//E1/2/3
                   }
                   else if(2==iresult)
                   {
                       qresult = QString("E2");//E1/2/3
                   }
                   else if(3==iresult)
                   {
                       qresult = QString("E3");//E1/2/3
                   }
                   else if(4==iresult)
                   {
                       qresult = QString("E4");//run overtime
                   }
                   m_ilockrun = 0;
                   QByteArray qsend = (QString(tr("CCD:P%1").arg(itrgnum))+qresult).toLatin1();
                   tcpServerConnection->write(qsend);
                   ShowLog(nullptr,QString("S:")+qsend);
                   double ds = m_pmanager->GetParserValue(QString("ds"));

                   if(ds>2)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }
                   else if(ds>1&&iresult>0)
                   {
                       QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                       if(pimage)
                       {
                           QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                           mkdir(QString(tr("D:\\ORG\\")));
                           QDateTime now = QDateTime::currentDateTime();
                           QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                           QString qstrdate =  QString(tr("D:\\ORG\\"))+qyearmd;
                           mkdir(qstrdate);
                           mkdir(qstrdate+qstrp);
                           QString qsavefile = qstrdate+qstrp+QString(tr("\\"))+qstrtimes+QString(".jpg");
                           pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                       }
                   }

                }

        }
    }
    else if(qtrgnum.mid(0,10)==QString("CCD:TrayId"))
    {
        QString qcoderesult = m_pmanager->getcodeparserstring();
        QString qresult=QString("CCD:T")+qcoderesult;
        QByteArray qsend =qresult.toLatin1();
        tcpServerConnection->write(qsend);
        ShowLog(0,QString("S:")+qresult);
    }
    else if(qtrgnum.mid(0,8)==QString("CCD:Data"))
    {
        QString qstationnum = qtrgnum.mid(9);
        int itrigstation = qstationnum.toInt();
        m_pmanager->SetParserValue(QString("dstationnum"),itrigstation);
        ShowLog(0,QString("Get:Station %1").arg(itrigstation));
        QString qtrig = qtrgnum.mid(8,1);
        if(qtrig==QString("R"))
            runopt("DataR");
        else if(qtrig==QString("L"))
            runopt("DataL");
        else
            runopt("Data");

        double dx1,dy1,dr1;
         dx1 = m_pmanager->GetParserValue(QString("dx1"));
         dy1 = m_pmanager->GetParserValue(QString("dy1"));
         dr1 = m_pmanager->GetParserValue(QString("dr1"));

        double dx2,dy2,dr2;
        dx2 = m_pmanager->GetParserValue(QString("dx2"));
        dy2 = m_pmanager->GetParserValue(QString("dy2"));
        dr2 = m_pmanager->GetParserValue(QString("dr2"));
        double dx3,dy3,dr3;
        dx3 = m_pmanager->GetParserValue(QString("dx3"));
        dy3 = m_pmanager->GetParserValue(QString("dy3"));
        dr3 = m_pmanager->GetParserValue(QString("dr3"));
        double dx4,dy4,dr4;
        dx4 = m_pmanager->GetParserValue(QString("dx4"));
        dy4 = m_pmanager->GetParserValue(QString("dy4"));
        dr4 = m_pmanager->GetParserValue(QString("dr4"));
        double dx5,dy5,dr5;
        dx5 = m_pmanager->GetParserValue(QString("dx5"));
        dy5 = m_pmanager->GetParserValue(QString("dy5"));
        dr5 = m_pmanager->GetParserValue(QString("dr5"));


        double dx7,dy7,dr7;
        dx7 = m_pmanager->GetParserValue(QString("dx7"));
        dy7 = m_pmanager->GetParserValue(QString("dy7"));
        dr7 = m_pmanager->GetParserValue(QString("dr7"));
        double dallvalue;
        dallvalue = m_pmanager->GetParserValue(QString("allresult"));
        QString qerrormsg;

        QString qcoderesult = m_pmanager->getcodeparserstring();
        QByteArray qsend;
        QString qsend1;
        QString qsfilename = tr("坐标异常");
        if(dallvalue<1)
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+qsfilename+QString(tr("\",\"Layer_Pos\":["));
        else
            qsend1 = QString(tr("{\"Cmd\":68,\"ErrMsg\":\""))+QString(tr("\","));

        QString qsend2 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr1, 0, 'f').arg(dx1, 0, 'f').arg(dy1, 0, 'f'));
        QString qsend3 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr2, 0, 'f').arg(dx2, 0, 'f').arg(dy2, 0, 'f'));
        QString qsend4 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr3, 0, 'f').arg(dx3, 0, 'f').arg(dy3, 0, 'f'));
        QString qsend5 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3},").arg(dr4, 0, 'f').arg(dx4, 0, 'f').arg(dy4, 0, 'f'));
        QString qsend6 = QString(tr("{\"A\":%1,\"X\":%2,\"Y\":%3}").arg(dr5, 0, 'f').arg(dx5, 0, 'f').arg(dy5, 0, 'f'));
        QString qsend8 = QString(tr("\"Result\":%1,\"Tray_ID\":\"%2\",").arg(dallvalue).arg(qcoderesult));
        QString qsend9 = QString(tr("\"Tray_Pos\":{\"R\":%1,\"X\":%2,\"Y\":%3}}").arg(dr7, 0, 'f').arg(dx7, 0, 'f').arg(dy7, 0, 'f'));
        QString qsendx = qsend1 + qsend8 + qsend9;
        qsend = qsendx.toLocal8Bit();
        tcpServerConnection->write(qsend);
        ShowLog(nullptr,QString("S:")+qsend);
    }



}

void Dialog::ServerReadyRead_project_SUP()
{
    QByteArray qreadall = tcpServerConnection->readAll();

    QString qtrgnum=QString(qreadall);



    QString qstrig = m_pmanager->GetParserString("trig");
    QString qruntimelimit = m_pmanager->GetParserString("runtimelimit");
    QString qsaveimage = m_pmanager->GetParserString("saveimage");
    QString qngstring = m_pmanager->GetParserString("ngstring");
    QString statstring = m_pmanager->GetParserString("statstring");
    int iruntime = qruntimelimit.toInt();
    int isize = qstrig.size();
    if(isize>0)
    {
        if(qstrig!=QString(""))
            if(qtrgnum.mid(0,isize)==qstrig)
            {

                if(m_ilockrun<1)
                {
                    m_ilockrun = 1;
                    QElapsedTimer time;
                    time.restart();
                    int ielapsetime=0;
                    int ilimittime=iruntime;
                    QString qstrp;

                    //  WorkerThreadA m_workerThreada;
                    m_iruntimeok=0;
                    //     m_workerThreada.setrun(this,statstring);
                    //     m_workerThreada.start(QThread::HighestPriority);
                    m_pmanager->runstatestring();

                  //  while (ielapsetime < ilimittime
                  //          )//&&false!=pthd->isrun())
                  //  {
                  //    QThread::currentThread()->setPriority(QThread::IdlePriority);
                  //     QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
                  //     ielapsetime=time.elapsed();
                  //  }
                    double dvalue = 0;
                    int iresult= 0;
                    if(1)//false==pthd->isrun())
                    {
                        ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime));
                        dvalue = m_pmanager->GetParserValue(QString("result"));
                    }
                    else
                    {
                        ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime));
                        dvalue = 4;
                    }
                    iresult= dvalue;
                    QString qresult = m_pmanager->GetParserString("resultstring");

                    m_ilockrun = 0;
                    // m_thread.setresponse(qresult);
                    // QByteArray qsend = qresult.toLatin1();
                    // tcpServerConnection->write(qsend);
                    ShowLog(nullptr,QString("S:")+qresult);

                    if(qsaveimage==QString("yes"))
                    {
                        QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                        if(pimage)
                        {
                            QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                            mkdir(QString(tr("/media/cxy/Q/img/")));
                            QDateTime now = QDateTime::currentDateTime();
                            QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                            QString qstrdate =  QString(tr("/media/cxy/Q/img/"))+qyearmd;
                            mkdir(qstrdate);
                            mkdir(qstrdate+qstrp);
                            QString qsavefile = qstrdate+qstrp+QString(tr("/"))+qstrtimes+QString(".jpg");
                            pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                        }
                    }

                    // qresult=QString("test");
                    const QByteArray responseData = qresult.toUtf8();

                    tcpServerConnection->write(responseData);
                    ShowLog(nullptr,QString("S:")+responseData);
/*
                    m_thread.getserialport()->write(responseData);
                    if (m_thread.getserialport()->waitForBytesWritten(m_thread.getwaittime()))
                    {
                        ShowLog(nullptr,QString("show Request:")+m_thread.getrequest());
                        //! [10] //! [11] //! [12]
                    }
                    else
                    {
                        ShowLog(nullptr,tr("Wait write response timeout %1")
                                             .arg(QTime::currentTime().toString()));
                    }
*/

                }

            }

    }




}

void Dialog::startSlave(const QString &portName, int waitTimeout)
{
  //  m_runButton->setEnabled(false);
  //  m_statusLabel->setText(tr("Status: Running, connected to port %1.")
  //                         .arg(m_serialPortComboBox->currentText()));

    connect(&m_thread, &SlaveThread::request, this, &Dialog::showResponse);
    connect(&m_thread, &SlaveThread::error, this, &Dialog::processError);
    connect(&m_thread, &SlaveThread::timeout, this, &Dialog::processTimeout);
    connect(&m_thread, &SlaveThread::trig, this, &Dialog::trigTimeout);


   m_thread.startSlave(portName,waitTimeout);
}

void Dialog::showResponse(const QString &s)
{
    ShowLog(nullptr,QString("com response:")+s);
    //  activateRunButton();
    //  m_statusLabel->setText(tr("Status: Not running, %1.").arg(s));
    //  m_trafficLabel->setText(tr("No traffic."));
}
void Dialog::processError(const QString &s)
{
    ShowLog(nullptr,QString("com Error:")+s);
  //  activateRunButton();
  //  m_statusLabel->setText(tr("Status: Not running, %1.").arg(s));
  //  m_trafficLabel->setText(tr("No traffic."));
}

void Dialog::processTimeout(const QString &s)
{
  //  ShowLog(nullptr,QString("process :")+s);

 //   m_statusLabel->setText(tr("Status: Running, %1.").arg(s));
 //   m_trafficLabel->setText(tr("No traffic."));
}
void Dialog::ComReadyRead_project_SUP(const QString &qtrgnum)
{

    QString qstrig = m_pmanager->GetParserString("trig");
    QString qruntimelimit = m_pmanager->GetParserString("runtimelimit");
    QString qsaveimage = m_pmanager->GetParserString("saveimage");
    QString qngstring = m_pmanager->GetParserString("ngstring");
    QString statstring = m_pmanager->GetParserString("statstring");
    int iruntime = qruntimelimit.toInt();
    int isize = qstrig.size();
    if(isize>0)
    {
        if(qstrig!=QString(""))
        if(qtrgnum.mid(0,isize)==qstrig)
        {

            if(m_ilockrun<1)
            {
                    m_ilockrun = 1;
                    QElapsedTimer time;
                    time.restart();
                    int ielapsetime=0;
                   int ilimittime=iruntime;
                    QString qstrp;

//  WorkerThreadA m_workerThreada;
                  m_iruntimeok=0;
                  //     m_workerThreada.setrun(this,statstring);
                  //     m_workerThreada.start(QThread::HighestPriority);
                 m_pmanager->runstatestring();

                      while (ielapsetime < ilimittime
                       )//&&false!=pthd->isrun())
                        {
                           QThread::currentThread()->setPriority(QThread::IdlePriority);
                          QCoreApplication::processEvents(QEventLoop::AllEvents, 50);

                          ielapsetime=time.elapsed();
                       }
                        double dvalue = 0;
                        int iresult= 0;
                        if(1)//false==pthd->isrun())
                       {
                           ShowLog(nullptr,QString("run:intime %1ms").arg(ielapsetime));
                           dvalue = m_pmanager->GetParserValue(QString("result"));
                       }
                       else
                       {
                           ShowLog(nullptr,QString("run:outtime %1ms").arg(ielapsetime));
                           dvalue = 4;
                       }
                       iresult= dvalue;
                       QString qresult = m_pmanager->GetParserString("resultstring");

                       m_ilockrun = 0;
                      // m_thread.setresponse(qresult);
                      // QByteArray qsend = qresult.toLatin1();
                      // tcpServerConnection->write(qsend);
                       ShowLog(nullptr,QString("S:")+qresult);

                       if(qsaveimage==QString("yes"))
                       {
                           QImage *pimage = m_pmanager->GetParserImage(QString("aimage"));
                           if(pimage)
                           {
                               QString qstrtimes = QTime::currentTime().toString("hh_mm_ss");
                               mkdir(QString(tr("/media/cxy/Q/img/")));
                               QDateTime now = QDateTime::currentDateTime();
                               QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
                               QString qstrdate =  QString(tr("/media/cxy/Q/img/"))+qyearmd;
                               mkdir(qstrdate);
                               mkdir(qstrdate+qstrp);
                               QString qsavefile = qstrdate+qstrp+QString(tr("/"))+qstrtimes+QString(".jpg");
                               pimage->save(qsavefile,"JPEG");ShowLog(0,QString("save:")+qsavefile);
                           }
                       }

                      // qresult=QString("test");
                       const QByteArray responseData = qresult.toUtf8();
                       m_thread.getserialport()->write(responseData);
                       if (m_thread.getserialport()->waitForBytesWritten(m_thread.getwaittime()))
                       {
                           ShowLog(nullptr,QString("show Request:")+m_thread.getrequest());
                           //! [10] //! [11] //! [12]
                       }
                       else
                       {
                            ShowLog(nullptr,tr("Wait write response timeout %1")
                                            .arg(QTime::currentTime().toString()));
                       }


            }

        }

    }



}


void Dialog::trigTimeout(const QString &s)
{
    m_qslavestr=s;
    ShowLog(nullptr,QString("com trig:")+m_qslavestr);
    ComReadyRead_project_SUP(m_qslavestr);
   // m_timer.start(20, this);

}


void Dialog::timerEvent(QTimerEvent *event)
{
    //
    if(0)
    {
        int itrgnum=getsofttrig();
        if(itrgnum!=m_igetrun)
        {
            if(m_ilockrun<1)
            {
               m_ilockrun = 1;

               m_pmanager->SetParserValue("trignum",itrgnum);
               m_igetrun =itrgnum;

               runopt("main");

               m_itrgnum=m_itrgnum+1;

               ShowLog(nullptr,tr("trig %1").arg(m_itrgnum));

               QString qcoderesult0 = m_pmanager->getcodeparsernumstring(0); ShowLog(nullptr,tr("c0:")+qcoderesult0);
               QString qcoderesult1 = m_pmanager->getcodeparsernumstring(1); ShowLog(nullptr,tr("c1:")+qcoderesult0);
               QString qcoderesult2 = m_pmanager->getcodeparsernumstring(2); ShowLog(nullptr,tr("c2:")+qcoderesult0);
               QString qcoderesult3 = m_pmanager->getcodeparsernumstring(3); ShowLog(nullptr,tr("c3:")+qcoderesult0);
               QString qcoderesult4 = m_pmanager->getcodeparsernumstring(4); ShowLog(nullptr,tr("c4:")+qcoderesult0);
               QString qcoderesult5 = m_pmanager->getcodeparsernumstring(5); ShowLog(nullptr,tr("c5:")+qcoderesult0);
               QString qcoderesult6 = m_pmanager->getcodeparsernumstring(6); ShowLog(nullptr,tr("c6:")+qcoderesult0);
               QString qcoderesult7 = m_pmanager->getcodeparsernumstring(7); ShowLog(nullptr,tr("c7:")+qcoderesult0);
               QString qcoderesult8 = m_pmanager->getcodeparsernumstring(8); ShowLog(nullptr,tr("c8:")+qcoderesult0);
               QString qcoderesult9 = m_pmanager->getcodeparsernumstring(9); ShowLog(nullptr,tr("c9:")+qcoderesult0);

               m_ilockrun = 0;
            }
        }


    }
    if(event->timerId() == m_cxvisiontimer.timerId())
    {
        updateview();
    }
 #ifdef CXVISIONSERVERLICENSE
    else if(event->timerId() == m_lstimer.timerId())
    {
        QString qstr = tr("%1").arg(rand());
        m_licstcpClient.write(qstr.toLocal8Bit());
      //  m_licstcpClient.write(QByteArray(1, '@'));
    }
#endif

 /*   else if(event->timerId() == m_timer.timerId())
    {
        if(2==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("2");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(3==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("3");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(4==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("4");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(5==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("5");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(6==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("6");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(7==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("7");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(8==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("8");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }
        else if(9==m_iruntimetrg)
        {
            m_iruntimetrg=0;
            m_timer.stop();
            runopt("9");
            m_iruntimeok=1;
            m_timer.start(25,this);
        }

    }

*/
    QObject::timerEvent(event);

}

void Dialog::ClientReadyRead_project()
{
    bytesReceived += int(m_ptcpClient->bytesAvailable());
    QByteArray qreadall = m_ptcpClient->readAll();
    QString qtrgnum=QString(qreadall);
    ShowLog(0,qtrgnum);

   int itrgnum = qtrgnum.toInt();
   m_pmanager->SetParserValue(QString("trignum"),itrgnum);
   double dvalue = m_pmanager->GetParserValue(QString("result"));
   int iresult= dvalue;
   QByteArray qsend = QString(tr("%1").arg(iresult)).toLatin1();
   m_ptcpClient->write(qsend);
   runopt("main");

}
void Dialog::ServerConnection_Serial()
{

  //  tcpServerConnection  = tcpServer.nextPendingConnection();

    //m_pconnection_serial = new CxConnection_serial(this,1);//server 1

    //CxConnection *pconnect = GetActiveConnect();
    //if(NULL==pconnect)
    //    SetActiveConnect(pconnect);

     //pconnection->connectisok();

    quint16 iport2 = 82;
    QHostAddress hostadress2 = QHostAddress( QString("192.168.1.100"));

    QString cxtest =QString(tr("Accepted connection: ")) + hostadress2.toString() + QString(tr(" Port: %1").arg(iport2));

    serverStatusLabel->setText(cxtest);

    ShowLog(0,cxtest);
}
void Dialog::ClientConnection_Serial()
{

    m_ptcpClient = new QTcpSocket;

    clientStatusLabel->setText(tr("Connecting"));

    QHostAddress qaddress;

    m_serverip = adminiEdit->text();

    m_serverport = tr("82") ;

    QStringList	alistparm  = m_serverip.split(QLatin1String(":"));

    if(alistparm.size()>=2)
    {
        m_serverip = alistparm.at(0);
        m_serverport = alistparm.at(1);
    }

    if(m_serverip=="")
    {
        qaddress.setAddress(QLatin1String("192.168.1.2"));//192.168.1.2"));
        m_serverip = QLatin1String("192.168.1.2");//192.168.1.2");
    }
    else
        qaddress.setAddress(m_serverip);

    //m_pconnection_serial = new CxConnection_serial(this,m_ptcpClient);//server 1

   // m_pcurrentconnect = m_pconnection_serial;

    quint16 iport2 = 82;
    QHostAddress hostadress2 = QHostAddress( QString("192.168.1.100"));

    QString cxtest =QString(tr("Accepted connection: ")) + hostadress2.toString() + QString(tr(" Port: %1").arg(iport2));

    serverStatusLabel->setText(cxtest);

    ShowLog(0,cxtest);
}

void Dialog::ClientIsConnection()
{  

    quint16 iport2 =  m_ptcpClient->localPort();
	
	QHostAddress hostadress2 =  m_ptcpClient->localAddress();
 
	QString cxtest = hostadress2.toString() + QString(tr(" Port: %1").arg(iport2)) + QString(tr("connection be Accepted "))  ;

    serverStatusLabel->setText(cxtest);
 
}

void Dialog::robotcalibdlg()
{
  // m_robotcalibdialog = new RobotCalibDialog(m_pmanager);// calibdialog;
  // m_robotcalibdialog->show();
 
}
void Dialog::cameracalibdlg()
{
 //  m_cameracalibdialog = new CameraCalibDialog(m_pmanager);// calibdialog;
 //  m_cameracalibdialog->show();

}



void Dialog::SendMessageToUser(const QString &qsmsg)
{
	CxConnection *pconnect = GetActiveConnect();
	if(pconnect!=0)
		pconnect->sendMessage(qsmsg);

}
void Dialog::SendComm(const QString &qcomm)
{ 	
    CxConnection *pconnect = GetActiveConnect();
	if(pconnect!=0) 
        AddDuty(pconnect,qcomm);
}

void Dialog::setEditText(const QString &str)
{
    CommandEdit->setText(str);
}
void Dialog::closeflash()
{
      m_pmanager->closeflash();

}
void Dialog::resetrun()
{
    hide();m_pdialogopt->release();
    m_pmanager->resetparser();
    m_pdialogopt = 0;
    m_pdialogopt = m_pmanager->getopt();
    if(0!=m_pdialogopt)
        m_pdialogopt->setdialog(this);
    show();
    showMaximized();
    ShowLog(0,tr("reset run ok"));
}
void Dialog::viewparserlist(const char *pchar)
{
    #ifdef BrowWin
     m_pageviewlist[0]->parserlink(pchar);

    QStringList astrlist = CreateurlList(m_pageviewlist[0]->GetLink("a","href"),
            m_pageviewlist[0]->currentTab()->url());

    CreateDateList(astrlist,m_igaptime,m_igaptime);//+100s begin and gap 100
#endif
}
void Dialog::viewrunjavascript(const char *pchar)
{
    #ifdef BrowWin
     m_pageviewlist[0]->PageRunJavaScript(pchar);
#endif

}

void Dialog::AddDutyfile()
{
    //local duty
    QFile file(getlocationstringx("./duty.txt"));

    if (file.open(QIODevice::ReadOnly))
    {
        QString line;
        QString strdate;
        QTextStream in(&file);
        while (!in.atEnd())
        {
            line = in.readLine();
            int i=0;
            //////////////////////////////////////////////////////////////////////////
            for(i = 0;i<line.size() ;i++)
            {
                QChar achar = line.at(i);
                if(achar=='|')
                {
                    goto ADDDUTYNEXT;
                }
            }

ADDDUTYNEXT:
            strdate = line.mid(0,i);
            if(i<line.size())
                line = line.mid(i+1);
            //////////////////////////////////////////////////////////////////////////
            //CxConnection *pconnect = GetActiveConnect();
            //if(NULL!=pconnect)
            //	AddDuty(pconnect,line,strdate);
            AddLoacalDuty(line,-2,strdate);
        }
    }

    //file.close();
{
    QFile file(getlocationstringx("./cduty.txt"));

    if (file.open(QIODevice::ReadOnly))
    {
        QString line;
        QString strdate;
        QTextStream in(&file);
        while (!in.atEnd())
        {
            line = in.readLine();
            int i=0;
            //////////////////////////////////////////////////////////////////////////
            for(i = 0;i<line.size() ;i++)
            {
                QChar achar = line.at(i);
                if(achar=='|')
                {
                    goto ADDDUTYNEXT0;
                }
            }
ADDDUTYNEXT0:
            strdate = line.mid(0,i);
            if(i<line.size())
                line = line.mid(i+1);
            //////////////////////////////////////////////////////////////////////////
            CxConnection *pconnect = GetActiveConnect();
            if(NULL!=pconnect)
                AddDuty(pconnect,line,strdate);
        }
    }
    //file.close();
}

}
void Dialog::sendDuty()
{
	QString fileName =
		QFileDialog::getOpenFileName(this, tr("Open File"),
		QDir::currentPath(),
		tr("ALL Files (*.*)"));
	if (fileName.isEmpty())
		return;
	QFile file(fileName);

	if (file.open(QIODevice::ReadOnly)) 
	{
		QString line;
		QString strdate;
		QTextStream in(&file);
		while (!in.atEnd()) 
		{
			line = in.readLine();
            int i=0;
			//////////////////////////////////////////////////////////////////////////
            for(i = 0;i<line.size() ;i++)
			{
				QChar achar = line.at(i);
				if(achar=='|')
				{
					goto ADDDUTYNEXT;
				}
			}
			
ADDDUTYNEXT:
			strdate = line.mid(0,i);
			if(i<line.size())
				line = line.mid(i+1);
			//////////////////////////////////////////////////////////////////////////
            //CxConnection *pconnect = GetActiveConnect();
            //if(NULL!=pconnect)
            //	AddDuty(pconnect,line,strdate);
            AddLoacalDuty(line,-1,strdate);
		}
	}
    //file.close();
}
void Dialog::LoginOK()
{
	m_ilogin = 1;

	ShowLog(0,tr("[login ok]"));
}
void Dialog::SetClear()
{
 
	Clear();
}
void Dialog::SendPiece()
{
 
	//////////////////////////////////////////////////////////////////////////
	//server
    CxConnection * pactconnect = GetActiveConnect();
    QString  user ;
    if(0!=pactconnect)
    {
       user = pactconnect->GetUser();
       m_recorduser = user;
    }
    else
    {
        return ;
    }

    Send_LoadFile_Multi(user);
}


void Dialog::ServerGetFile()
{

}
void Dialog::ClientGetFile()
{

} 
void Dialog::updateProgress(const QString &qstrgos,qint64 numBytes,qint64 totalBytes)
{ 
    clientProgressBar->setMaximum(totalBytes);
    clientProgressBar->setValue(numBytes);
    clientStatusLabel->setText(qstrgos + tr(" %1MB").arg(numBytes / (1024 * 1024)));
}
QByteArray Dialog::loadfilestring(const QString& file) const
{
	QFile f(file);

	QByteArray qfilereads;

	const int size = f.size();
	//const int size = m_lastFileState.size = f.size();
	if ( !f.open(QFile::ReadOnly) )
	{
		return QByteArray();
	}
	if ( size < 500000 )
	{
		// instant load for files smaller than 500kb
		QByteArray d = f.readAll();
		f.close();
		return d;
	} 
	else
	{
		// load by chunks of 100kb otherwise to avoid huge peaks of memory usage
		// and driving mad the disk drivers
		int count = 0;
		QByteArray ba;
		do
		{
			ba = f.read(100000);
			count += ba.count();
			qfilereads += ba ;
		} while ( (count < size) && ba.count() );
		f.close();
		return qfilereads;
	}
}
void Dialog::CodeViewIni()
{
/*
    // QCE setup
    m_formats = new QFormatScheme("qxs/cpp.qxf", this);

    QDocument::setDefaultFormatScheme(m_formats);

    QLineMarksInfoCenter::instance()->loadMarkTypes("qxs/marks.qxm");

    m_session = new QEditSession("session", this);
    connect(m_session	, SIGNAL( restored(QEditor*) ),this, SLOT( restored(QEditor*) ) );

    m_snippetManager = new QSnippetManager(this);
    m_snippetManager->loadSnippetsFromDirectory("snippets");

    m_snippetBinding = new QSnippetBinding(m_snippetManager);

    //m_snippetEdit->setSnippetManager(m_snippetManager);

    m_languages = new QLanguageFactory(m_formats, this);
    m_languages->addDefinitionPath("qxs");


    m_editControl = new QCodeEdit(this);

    m_editControl->editor()->setInputBinding(m_snippetBinding);

    m_languages->setLanguage(m_editControl->editor(), "*.cpp");
    m_editControl
        ->addPanel("Line Mark Panel", QCodeEdit::West, true)
        ->setShortcut(QKeySequence("F6"));

    m_editControl
        ->addPanel("Line Number Panel", QCodeEdit::West, true)
        ->setShortcut(QKeySequence("F11"));

    m_editControl
        ->addPanel("Fold Panel", QCodeEdit::West, true)
        ->setShortcut(QKeySequence("F9"));

    m_editControl
        ->addPanel("Line Change Panel", QCodeEdit::West, true)
        ; //->setShortcut(QKeySequence("F11"));

    m_editControl
        ->addPanel("Status Panel", QCodeEdit::South, true);

    m_editControl
        ->addPanel("Goto Line Panel", QCodeEdit::South);

    m_editControl
        ->addPanel("Search Replace Panel", QCodeEdit::South);

    connect(m_editControl->editor()	, SIGNAL( contentModified(bool) ),
            this					, SLOT  ( setWindowModified(bool) ) );

    m_session->addEditor(m_editControl->editor());

    m_editor = m_editControl->editor();
    //m_stack->insertWidget(1, m_editControl->editor());
    m_blayout->addWidget(m_editControl->editor());
*/
    // create toolbars
    /*
    m_edit = new QToolBar(tr("Edit"), this);
    m_edit->setIconSize(QSize(24, 24));
    m_edit->addAction(m_editControl->editor()->action("undo"));
    m_edit->addAction(m_editControl->editor()->action("redo"));
    m_edit->addSeparator();
    m_edit->addAction(m_editControl->editor()->action("cut"));
    m_edit->addAction(m_editControl->editor()->action("copy"));
    m_edit->addAction(m_editControl->editor()->action("paste"));
    m_edit->addSeparator();
    m_edit->addAction(m_editControl->editor()->action("indent"));
    m_edit->addAction(m_editControl->editor()->action("unindent"));
    //m_edit->addAction(m_editControl->editor()->action("comment"));
    //m_edit->addAction(m_editControl->editor()->action("uncomment"));
    addToolBar(m_edit);
    m_edit->hide();
    */
    /*
    m_find = new QToolBar(tr("Find"), this);
    m_find->setIconSize(QSize(24, 24));
    m_find->addAction(m_editControl->editor()->action("find"));
    //find->addAction(m_editControl->editor()->action("findNext"));
    m_find->addAction(m_editControl->editor()->action("replace"));
    m_find->addAction(m_editControl->editor()->action("goto"));
    addToolBar(m_find);
    m_find->hide();


    // settings restore
    QSettings settings;

    // general settings page

    settings.beginGroup("display");

    settings.beginGroup("panels");

    settings.endGroup();

    bool wrap = settings.value("dynamic_word_wrap", false).toBool();
   // chkWrap->setChecked(wrap);
    //m_editControl->editor()->setFlag(QEditor::LineWrap, wrap);

    bool cmwwb = settings.value("cursor_movement_within_wrapped_blocks", true).toBool();
  //  chkMoveInWrap->setChecked(cmwwb);
    //m_editControl->editor()->setFlag(QEditor::CursorJumpPastWrap, cmwwb);

    settings.endGroup();

    int flags = QEditor::defaultFlags();

    if ( wrap )
        flags |= QEditor::LineWrap;
    else
        flags &= ~QEditor::LineWrap;

    if ( cmwwb )
        flags |= QEditor::CursorJumpPastWrap;
    else
        flags &= ~QEditor::CursorJumpPastWrap;

    if ( settings.value("auto_indent", true).toBool() )
        flags |= QEditor::AutoIndent;
    else
        flags &= ~QEditor::AutoIndent;

    QEditor::setDefaultFlags(flags);

    //spnRecent->setValue(settings.value("files/max_recent", 10).toInt());
    //updateRecentFiles();

    // editor settings page
   // m_config = new QEditConfig(settingsStack);
    settings.beginGroup("edit");
    //m_config->loadKeys(readSettingsMap(settings));
    settings.endGroup();
    //m_config->apply();
    //settingsStack->addWidget(m_config);

    // syntax settings page
  //  m_formatConfig = new QFormatConfig(settingsStack);
  //  m_formatConfig->addScheme("global", m_formats);

    QStringList langs = m_languages->languages();

//    foreach ( const QString& lang, langs )
//    {
//        const QLanguageFactory::LangData& ld = m_languages->languageData(lang);

//        if ( ld.s != m_formats )
 //       {
//            m_formatConfig->addScheme(ld.lang, ld.s);
//        }
 //   }

 //   settingsStack->addWidget(m_formatConfig);

    // restore GUI state
    settings.beginGroup("gui");

    settings.endGroup();
    m_session->restore(); */
}
void Dialog::SaveParser()
{
    QString strcur = m_pmanager->getcurrentstatename();
    if(""==strcur)
    {
        ShowLog(nullptr,QString(tr("null name!")));
        return;
    }
    QString strname = "./"+strcur+".cxut";
    m_pmanager->saveeditcode(m_editor->toPlainText().toStdString().c_str()
                              ,strname.toStdString().c_str()
                              );
    ShowLog(nullptr,strname + QString(tr(" save ok")));
}
void Dialog::editManage()
{
    m_pmanager->editviewenable();
}
void Dialog::TestParser()
{
    visionmanager::g_runelapsed.start();

    m_pmanager->clearos();

    m_pmanager->runstringcode(m_editor->toPlainText().toStdString().c_str());

    //ServerTextEdit->setPlainText(m_pmanager->getoutputstring());
    ShowLog(0,m_pmanager->getoutputstring());
}
void Dialog::TestParserX()
{
    m_pmanager->runstringcodex(m_editor->toPlainText().toStdString().c_str());
    ShowLog(0,m_pmanager->getoutputstring());
}
void Dialog::SetCommandEditText(QString &qstr)
{
    CommandEdit->setText(qstr);
}
void Dialog::SetTextEditText(QString &qstr)
{
    SetEdit->setText(qstr);
}
void Dialog::SetValueEditText(QString &qstr)
{
    ValueEdit->setText(qstr);
}


void Dialog::SetParserValue(QString qstr,double dvalue)
{
    m_pmanager->SetParserValue(qstr,dvalue);


}
void Dialog::SetValue()
{
    m_pmanager->SetParserValue(SetEdit->text(),ValueEdit->text().toDouble());
    ShowLog(0,m_pmanager->getoutputstring());
}
void Dialog::GetValue()
{
   double dvalue = m_pmanager->GetParserValue(SetEdit->text());
   ShowLog(0,tr("%1").arg(dvalue));
   ValueEdit->setText(tr("%1").arg(dvalue));
}

double Dialog::GetDValue(const char *pname)
{
    double dvalue = m_pmanager->GetParserValue(pname);
    return  dvalue;
}
void Dialog::savefilestring(const QString& fn)
{
	QFile f(fn);

	if ( !f.open(QFile::WriteOnly) )
	{
		return;
	}

	f.write(m_databuf);
	f.close();
}
void Dialog::getonepiecefile(int icp,int ipsize,int itolsize,const QString &qname,const QString &qid,const QByteArray &qcontent)
{
	m_piecefile.m_istatus[icp] = -1;
	m_piecefile.icurpiece = icp;
	m_piecefile.pieceLength = ipsize;
	m_piecefile.totallength = itolsize;
	m_piecefile.qsname = qname;
	m_piecefile.qsid = qid;
	m_piecefile.m_qcontents[icp] = qcontent;

	//GetPieceFile()->icurpiece = icp;
	//GetPieceFile()->pieceLength = ipsize;
	//GetPieceFile()->totallength = itolsize;
	//GetPieceFile()->qsname = qname;
}
int Dialog::getonepiecefilex(int icp,int ipsize,int itolsize,const QByteArray &qname,const QByteArray &qid,const QByteArray &qcontent)
{

    int imaxlen = 0;
    if(ipsize>0)
        imaxlen = (itolsize/ipsize) + ((itolsize%ipsize)>0?1:0);
    else
        imaxlen = 1;

    int inum = 0;

    int ipicfilesize = m_piecefilelist.size();


    ipicfilesize = m_piecefilelist.size();
    int icurfilenum  = -1;
    for(int i=0;i<ipicfilesize;i++)
    {
        if(m_piecefilelist[i].qsname == qname)
        {
            icurfilenum = i;
        }
    }
    if(icurfilenum>-1)
    {
        if(m_piecefilelist[icurfilenum].m_istatus[icp]!= -1)
        {
            m_piecefilelist[icurfilenum].m_istatus[icp] = -1;
            m_piecefilelist[icurfilenum].icurpiece = icp;
            m_piecefilelist[icurfilenum].pieceLength = ipsize;
            m_piecefilelist[icurfilenum].totallength = itolsize;
            m_piecefilelist[icurfilenum].qsname = qname;
            m_piecefilelist[icurfilenum].qsid = qid;
            m_piecefilelist[icurfilenum].m_qcontents[icp] = qcontent;
            m_piecefilelist[icurfilenum].m_isfinish = 0;
        }
        for(int i=0;i<imaxlen;i++)
        {
            if(-1==m_piecefilelist[icurfilenum].m_istatus[i])
            {
                inum = inum + 1;
            }
        }
    }
    else
    {
        CxPieceFile apiecefile;
        m_piecefilelist.push_back(apiecefile);
        icurfilenum = 0;
        m_piecefilelist[0].m_istatus[icp] = -1;
        m_piecefilelist[0].icurpiece = icp;
        m_piecefilelist[0].pieceLength = ipsize;
        m_piecefilelist[0].totallength = itolsize;
        m_piecefilelist[0].qsname = qname;
        m_piecefilelist[0].qsid = qid;
        m_piecefilelist[0].m_qcontents[icp] = qcontent;
        m_piecefilelist[0].m_isEND = 0;
        m_piecefilelist[0].m_isfinish = 0;
        inum = 1;

    }
//
    if(inum>=imaxlen)
    {
        if(0==m_piecefilelist[icurfilenum].m_isfinish)
        {
            m_piecefilelist[icurfilenum].m_isfinish = 1;

            QByteArray getbuf;
            int itolsize = m_piecefilelist[icurfilenum].totallength;
            int ipsize =m_piecefilelist[icurfilenum].pieceLength;
            int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
            for(int i=0;i<ipiecenum;i++)
            {
               getbuf  += m_piecefilelist[icurfilenum].m_qcontents[i];
            }
            //
            QByteArray igettype;
            QByteArray igetstring;
            for(int i = 0;i<qname.size() ;i++)
            {
                QChar achar = qname.at(i);
                if(achar=='_')
                {
                    igettype = qname.mid(0,i);
                    igetstring = qname.mid(i+1);
                    break;
                }
            }
            if(igettype=="file")
            {
                Get_SaveFileSend(igetstring,getbuf);
                inum = 99999999;
                m_piecefilelist[icurfilenum].m_istatus.clear();
                m_piecefilelist[icurfilenum].m_qcontents.clear();
                m_piecefilelist[icurfilenum].m_isEND = 1;

            }
            else if(igettype=="Tfile")
            {
               int iends = Get_SaveTFileSend(igetstring,getbuf);

               if(0==iends)
               {
                   inum = 99999999;

                   if(m_getfiles.size()>4)
                   {
                       ShowLog(0,tr("clear get file map"));
                       m_getfiles[0].m_filename.clear();
                       m_getfiles[0].m_istatus.clear();
                       m_getfiles[0].m_bwrite.clear();
                       m_getfiles[0].m_getfilebytes.clear();
                       m_getfiles.pop_front();

                   }

                   m_piecefilelist[icurfilenum].m_istatus.clear();
                   m_piecefilelist[icurfilenum].m_qcontents.clear();
                   m_piecefilelist[icurfilenum].m_isEND = 1;
               }
                else if(1==iends)
                {
                   inum = 90000000;

                   if(m_getfiles.size()>0)
                   {
                       m_getfiles[0].m_filename.clear();
                       m_getfiles[0].m_istatus.clear();
                       m_getfiles[0].m_bwrite.clear();
                       m_getfiles[0].m_getfilebytes.clear();
                       m_getfiles.pop_front();

                   }

                   m_piecefilelist[icurfilenum].m_istatus.clear();
                   m_piecefilelist[icurfilenum].m_qcontents.clear();
                   m_piecefilelist[icurfilenum].m_isEND = 1;
               }
               else if(2==iends)
                   inum = 90000001;
               else if(10==iends)
                   inum = 90000010;
               else inum = 90000002;
            }
            else if(igettype=="image")
            {
                Get_SaveImageSend(igetstring,getbuf);
                inum = 99999999;
                m_piecefilelist[icurfilenum].m_istatus.clear();
                m_piecefilelist[icurfilenum].m_qcontents.clear();
                m_piecefilelist[icurfilenum].m_isEND = 1;
            }
            else if(igettype=="imageframe")
            {
                Get_SaveImageFrameSend(igetstring,getbuf);
                inum = 99999999;
                m_piecefilelist[icurfilenum].m_istatus.clear();
                m_piecefilelist[icurfilenum].m_qcontents.clear();
                m_piecefilelist[icurfilenum].m_isEND = 1;

            }
            else
            {
                inum = 99999999;
            }
            ////////////

            int ipicfilesize0 = m_piecefilelist.size();
            if(ipicfilesize0>5)
                m_piecefilelist.pop_front();
        }
        else
        {
            inum = 90000002;
        }
    }

//

    return inum;
    //GetPieceFile()->icurpiece = icp;
    //GetPieceFile()->pieceLength = ipsize;
    //GetPieceFile()->totallength = itolsize;
    //GetPieceFile()->qsname = qname;
}

inline int Dialog::getpiecetransferwaittime(int icp)
{
    QString qstime = tr("%1").arg(Dialog::GetGolbalTime());
    //QDateTime::currentDateTime().toString(QLatin1String("MMddhhmmss"));

	int itimes = GetPieceFile()->m_istatus[icp];
	if(itimes>0)	
	{
		int icurtimes = qstime.toInt() - itimes ;
		return icurtimes;
	}
	else if(itimes==0)
	{
		GetPieceFile()->m_istatus[icp] = qstime.toInt() - 1;
		return 0;	
	}
 
}
inline int Dialog::piececanbetransfer(int icp)//1 can be transfer, 0 no be transfer
{ 
	int icsize = m_piecefile.m_qcontents[icp].size();
	if(icsize>0)
		return 0;
	int ipasstime = getpiecetransferwaittime(icp);
	if(0== ipasstime)
		return 1;
	if(ipasstime>30)//transfer over 30 s no finish to retransfer
	{
		return 1;
	} 
	else 
		return 0;
}

int Dialog::getfilefinish()
{ 
	return	m_piecefile.m_isfinish ;
}
void Dialog::settransferover()
{
	m_piecefile.m_isfinish = 2;
}
int Dialog::getnextpiecenum()
{ 
	int icurpiece = m_piecefile.icurpiece;
	int istatus = piececanbetransfer(icurpiece+1);//m_piecefile.m_qcontents[icurpiece+1].size();
	if(istatus!=1)
	{
		int itolsize = m_piecefile.totallength;
		int ipsize =m_piecefile.pieceLength;

		int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);

		for(int i=0;i<ipiecenum;i++)
		{ 
			istatus =  piececanbetransfer(i);//m_piecefile.m_qcontents[i].size();
			if(istatus!=1)
				return i;
		}

		m_piecefile.m_isfinish = 1;
		return -1;
	}
	else
		return icurpiece+1;
}
int Dialog::getfinishnum(int itotalnum)
{ 
	int inum = 0;
	for(int i=0;i<itotalnum;i++)
	{
		if(-1==m_piecefile.m_istatus[i])
		{
			inum = inum + 1;
		}
	}
	return inum;
}
void Dialog::Get_SaveFileSend(const QString &qname,const QByteArray&databuf  )
{
    m_databuf =  qUncompress(databuf);

	QFileInfo afile(qname);
	
	QString astrfile = afile.fileName();
	QString endName = afile.suffix(); 
	QString getfilename = afile.completeBaseName()+tr(".")+afile.completeSuffix();
	if(afile.completeBaseName()!=tr("") )
	{
		savefilestring(getlocationstringx("./file/"+getfilename));	
	}
	else
	{
		QDateTime now = QDateTime::currentDateTime();
		QString qyear = now.toString(QLatin1String("yyyy"));
		QString qmh = now.toString(QLatin1String("MM"));
		QString qdy = now.toString(QLatin1String("dd"));
        //int ih = QTime::currentTime().hour();
        //int im = QTime::currentTime().minute();
        //int is = QTime::currentTime().second();
		QString qfilenamex = qyear + tr("_") +qmh + tr("_") +qdy + QTime::currentTime().toString("_hh_mm_ss");
		savefilestring(getlocationstringx("./file/"+qfilenamex));	
	}
}
void Dialog::Get_SaveDateFileSend(const QString &qname )
{
	int itolsize = m_piecefile.totallength;
	int ipsize =m_piecefile.pieceLength;

	if(itolsize==0
		||ipsize==0)
		return;
		
	int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
	m_databuf.clear();
	for(int i=0;i<ipiecenum;i++)
	{
		m_databuf += m_piecefile.m_qcontents[i];	
	}

	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;

	m_databuf =  qUncompress(m_databuf);

	QFileInfo afile(qname);

	QString astrfile = afile.fileName();
	QString endName = afile.suffix(); 
	QString getfilename = afile.completeBaseName()+tr(".")+afile.completeSuffix();
	//if(afile.completeBaseName()!=tr("") )
	//{
	//	savefilestring(getlocationstringx("./file/"+getfilename));	
	//}
	//else
	{
		QDateTime now = QDateTime::currentDateTime();
		QString qyear = now.toString(QLatin1String("yyyy"));
		QString qmh = now.toString(QLatin1String("MM"));
		QString qdy = now.toString(QLatin1String("dd"));
		int ih = QTime::currentTime().hour();
		int im = QTime::currentTime().minute();
		int is = QTime::currentTime().second();	
		QString qfilenamex = qyear + tr("_") +qmh + tr("_") +qdy + QTime::currentTime().toString("_hh_mm_ss_zzz")+getfilename;
		savefilestring(getlocationstringx("./file/"+qfilenamex));
		

	
	}
}
void Dialog::savefile(const QByteArray &qcontent,const QString &qname)
{
	m_databuf =  qcontent;
	savefilestring(getlocationstringx("./file/"+qname));
}
void Dialog::Get_SaveImageSend(const QByteArray &qname,const QByteArray &databuf)
{ 
    QByteArray qbw;
    QByteArray qbh;
    int i_num = 0;
    int iprenum = 0;
    for(int i = 0;i<qname.size() ;i++)
    {
        QChar achar = qname.at(i);
        if(achar=='_')
        {
            if(0==i_num)
            {
                qbw = qname.mid(iprenum,i-iprenum);
                iprenum = i + 1;
                i_num = i_num + 1;
            }
            else if(1==i_num)
            {
                qbh = qname.mid(iprenum,i-iprenum);
                iprenum = i + 1;
                i_num = i_num + 1;
                goto NEXTRUN3;
            }
        }
    }
    if(i_num<=1)
        qbh = qname.mid(iprenum);
NEXTRUN3:
    int iw =qbw.toInt();
    int ih =qbh.toInt();

    QByteArray adatabuf =  qUncompress(databuf);
    QImage image((uchar*)adatabuf.data(),iw,ih,QImage::Format_RGB16);
 
    setimage(image);
    ShowLog(0,tr("getimage %1 x%2 ").arg(iw).arg(ih));
}
void Dialog::Get_SaveImageFrameSend(const QByteArray &qname,const QByteArray &databuf)
{
    QByteArray qbw;
    QByteArray qbh;
    int i_num = 0;
    int iprenum = 0;
    for(int i = 0;i<qname.size() ;i++)
    {
        QChar achar = qname.at(i);
        if(achar=='_')
        {
            if(0==i_num)
            {
                qbw = qname.mid(iprenum,i-iprenum);
                iprenum = i + 1;
                i_num = i_num + 1;
            }
            else if(1==i_num)
            {
                qbh = qname.mid(iprenum,i-iprenum);
                iprenum = i + 1;
                i_num = i_num + 1;
                goto NEXTRUN3;
            }
        }
    }
    if(i_num<=1)
        qbh = qname.mid(iprenum);
NEXTRUN3:
    int iw =qbw.toInt();
    int ih =qbh.toInt();

    QByteArray adatabuf =  qUncompress(databuf);
    QImage image((uchar*)adatabuf.data(),iw,ih,QImage::Format_RGB16);

    setimage(image);
    ShowLog(0,tr("getimage %1 x%2 ").arg(iw).arg(ih));



#ifdef CXVISIONIMAGEVIEW
			if(NULL!=m_imageViewer)
			{ 
				m_imageViewer->loadimageframe(image);
			} 
#else
             setimageframe(image);
#endif
             ShowLog(0,tr("getimageframe %1 x%2 ").arg(iw).arg(ih));

}
void Dialog::Set_Clear(CxConnection*pconnect)
{

	pconnect->Clear();
	
	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;
 
	QPainter painter(&m_image); 
	painter.fillRect(m_image.rect(), Qt::black);
	painter.end();
	QPainter painter1(&m_resultImage); 
	painter1.fillRect(m_resultImage.rect(), Qt::black);
	painter1.end();
	QPainter painter2(&m_ioldimage); 
	painter2.fillRect(m_ioldimage.rect(), Qt::black);
	painter2.end();
}
void Dialog::Get_ShowPageSend()
{ 
	int itolsize = m_piecefile.totallength; 
	int ipsize =m_piecefile.pieceLength;

	if(itolsize==0
		||ipsize==0)
		return;
	int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
	m_databuf.clear();
	for(int i=0;i<ipiecenum;i++)
	{
		m_databuf += m_piecefile.m_qcontents[i];	
	}

	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;

	m_databuf =  qUncompress(m_databuf);	
#ifdef CXVISIONBSERVER 
	//if(NULL==m_pageview)
	//	return;
	QString strbuf = QString::fromUtf8(m_databuf);
	m_pageviewlist[0]->SetFrameViewHtml(strbuf);
#endif
}
void Dialog::Get_SqlSend(CxConnection*pconnect)
{
#ifdef CXVISIONBSERVER 

	int itolsize = m_piecefile.totallength; 
	int ipsize =m_piecefile.pieceLength;

	if(itolsize==0
		||ipsize==0)
		return;
	int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
	m_databuf.clear();
	for(int i=0;i<ipiecenum;i++)
	{
		m_databuf += m_piecefile.m_qcontents[i];	
	}

	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;

	m_databuf =  qUncompress(m_databuf);	

	//if(NULL==m_pageview)
	//	return;

	QString getliststr = m_databuf;

	ShowLog(0,getliststr);
 
	m_getlist = getliststr.split("\r\n") ;

	if(m_sqlbrower!=0)
	{
 
		 m_sqlbrower->AddRelationPage(m_strpage);
		 m_sqlbrower->AddPageStringList(m_getlist);
		 if(m_strpage!="")
		 {
			 m_sqlbrower->cxsql_writepage(m_strpage);
			 m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,m_strpage);
			 m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,m_strpage+tr("/"));
		 }
	}
	
	SetLoop(0,1);
	
#endif

	
}
void Dialog::Get_SqlxSend(CxConnection*pconnect)
{
	int itolsize = m_piecefile.totallength; 
	int ipsize =m_piecefile.pieceLength;

	if(itolsize==0
		||ipsize==0)
		return;
	int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
	
	m_databuf.clear();
	
	for(int i=0;i<ipiecenum;i++)
	{
		m_databuf += m_piecefile.m_qcontents[i];	
	}

	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;

	m_databuf =  qUncompress(m_databuf);	


	QString getliststr = m_databuf;

	ShowLog(0,getliststr);

	m_getlist = getliststr.split("\r\n") ;

#ifdef CXVISIONBSERVER 
	if(m_sqlbrower!=0)
	{
		if(m_getlist.size()>0)
		{ 
			switch(m_pagesnum)
			{
				default:
				case -5:
				{
					QString strpaserpage = m_getlist[0];
					ShowLog(0,tr("sqlx list-> :")+strpaserpage);
					m_getlist.pop_front();
					m_sqlbrower->AddRelationPage(strpaserpage);
					m_sqlbrower->AddPageStringList(m_getlist);
					if(strpaserpage!="")
					{
						m_sqlbrower->cxsql_writepage(strpaserpage);
						m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,strpaserpage);
						m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,strpaserpage+tr("/"));
						ShowLog(0,tr("SQLFinish ->Set visit ")+strpaserpage+tr("%1").arg(m_pagevisitnum));
					}
				}
				break;
				case -7:
				case -6:
				{
						QString strpaserpage = m_getlist[0];
						ShowLog(0,tr("sqlx list-> :")+strpaserpage);
						m_getlist.pop_front();
						m_sqlbrower->AddRelationPage(strpaserpage);
						m_sqlbrower->AddPageStringList(m_getlist);
						if(strpaserpage!="")
						{
							m_sqlbrower->cxsql_set_relation_value("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,strpaserpage);
							ShowLog(0,tr("SQLFinish ->Set visit ")+strpaserpage+tr("%1").arg(m_pagevisitnum));
						}
				
				
				}
				break;
			}
		}
	}
#endif




}
void Dialog::SetLoop(int inum,int ivalue)
{
	m_pagesrunfinish[inum] = ivalue; 
}
void Dialog::SetDateLoop(int inum,int ivalue,QString &qdate,QString &qstring)
{
	m_pagesrunfinish[inum] = ivalue; 
	m_pagesrundate[inum] = qdate;
	m_pagestring[inum] = qstring;
}
void Dialog::ResetDateLoop(QString &qdate,int ivalue)
{
	if(m_pagesrundate[0]==qdate)
		m_pagesrunfinish[0] = ivalue; 
	if(m_pagesrundate[1]==qdate)
		m_pagesrunfinish[1] = ivalue; 
	if(m_pagesrundate[2]==qdate)
		m_pagesrunfinish[2] = ivalue; 
	if(m_pagesrundate[3]==qdate)
		m_pagesrunfinish[3] = ivalue; 
}
void Dialog::SetSQLRecord(QString &qdate)
 {

#ifdef CXVISIONBSERVER 
	if(m_sqlbrower!=0)
	{
		QString strget;
		
		if(m_pagesrundate[0]==qdate)
			strget = m_pagestring[0];
		if(m_pagesrundate[1]==qdate)
			strget = m_pagestring[1];
		if(m_pagesrundate[2]==qdate)
			strget = m_pagestring[2];
		if(m_pagesrundate[3]==qdate)
			strget = m_pagestring[3];
			
		QString qsymd = QDateTime::currentDateTime().toString(QLatin1String("yyyyMMdd"));
		QString qstime = QTime::currentTime().toString(QLatin1String("hhmmss")); 
		m_sqlbrower->cxsql_writepage(strget);
		m_sqlbrower->cxsql_setpagevalue("datestr", qsymd + qstime/*"time"*/,strget); 
		ShowLog(0,tr("set datestr ")+strget);
	}
#endif

}
void Dialog::Get_SaveListSend()
{ 
	int itolsize = m_piecefile.totallength; 
	int ipsize =m_piecefile.pieceLength;

	if(itolsize==0
		||ipsize==0)
		return;
	int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
	m_databuf.clear();
	for(int i=0;i<ipiecenum;i++)
	{
		m_databuf += m_piecefile.m_qcontents[i];	
	}

	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.qsid ="";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.m_isfinish = 0;

	m_databuf =  qUncompress(m_databuf);	

 
	QString getliststr = m_databuf;
	
	ShowLog(0,getliststr);
	
	m_getlist.append(getliststr.split("\r\n")) ;
	m_getlist.removeDuplicates();
	//

	//
	
	//FILE *m_fp =NULL;
	//QString fileName("searchlink.txt");
	//if(m_fp!=NULL)
	//	return;
	//m_fp=fopen(fileName.toLocal8Bit(),"at");
	//for(int i=0;i<alistparm.size();i++)
	//fprintf(m_fp, alistparm[i].toLocal8Bit());
	//fclose(m_fp);
	//m_fp = NULL;
}
void Dialog::Run_Clear()
{
	ShowLog(0,tr("List Clear"));
	m_getlist.clear();
}
void Dialog::Run_PageElementClassic(const QString & qsfilesuffix,const QString & qsopt,const QString & qduty1,const QString & qduty2)
{
	QStringList filelist;
	//filter
	for(int i=0;i<m_getlist.size();i++)
	{ 
		QFileInfo qfileinf(m_getlist[i]); 
		QString qname = qfileinf.fileName();
		QString endName = qfileinf.suffix(); 

		if(endName==qsfilesuffix)
		{
			filelist.append(m_getlist[i]);
			ShowLog(0,qsfilesuffix+tr(":")+m_getlist[i]);
		}
	}
	//add duty
	for(int i=0;i<filelist.size();i++)
	{	
		CxConnection * pactconnect =GetActiveConnect();
		if(filelist[i]!=tr(""))
		{
			AddDuty(pactconnect,qsopt+tr(" ")+filelist[i]);
			if(qduty1!=tr(""))
			{
				AddDuty(pactconnect,qduty1);
				if(qduty2!=tr(""))
				{
					AddDuty(pactconnect,qduty2); 
				}
			}
		}
	}	 
}


void Dialog::Send_LoadFile(CxConnection *pconnect)
{
    QString fileName =
        QFileDialog::getOpenFileName(this, tr("Open File"),
        QDir::currentPath(),
        tr("ALL Files (*.*)"));

    if (fileName.isEmpty())
        return;

    pconnect->setbufx(loadfilestring(fileName)) ;

    Send_File(pconnect,fileName,pconnect->getbufx());

}


void Dialog::Send_LoadFile_Multi(const QString &user,const QString &qsdate)
{
	QString fileName =
		QFileDialog::getOpenFileName(this, tr("Open File"),
		QDir::currentPath(),
		tr("ALL Files (*.*)"));
	if (fileName.isEmpty())
		return;

    //pconnect->setbufx(loadfilestring(fileName)) ;

	Send_File_Multi(user,fileName,loadfilestring(fileName),qsdate);
    //	Send_File(pconnect,fileName,pconnect->getbufx());

}

void Dialog::PageFinish(const QString &qname,int itype,BrowserWindow*pview)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname);
	ShowLog(pconnect,"PageFinish "+ qname);
	if(pconnect!=NULL)
	{
			
		//AddDutyNoReply(pconnect,"sendfinish Duty,wget "+qname,geturldate(qname));
		//if(0==m_ics)
		if(1==pconnect->IScors())//server
		{ 
			//if(0==itype)
			//	pconnect->AddDuty_frontstr("sendfinish Duty,wget "+qname,geturldate(qname),2);
			//else if(1==itype)
			pconnect->AddMsg("pagefinish "+ sgetdate+tr(":") +qname);
		}
	}
	else
	{	
		 //if(0==m_ics)
		if(1==pconnect->IScors())//server
		{	
		//	ShowLog(0,"pagefinish"+qname);
			if(m_localdutylist.size()>0)
				m_localdutylist.pop_front();
		}
	}
	removeurllist(qname);
}
void Dialog::PageSQLFinish(const QString &qname,int itype,BrowserWindow*pview)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname);
	ShowLog(pconnect,"PageFinish "+ qname);
	if(pconnect!=NULL)
	{ 
		//AddDutyNoReply(pconnect,"sendfinish Duty,wget "+qname,geturldate(qname));
		//if(0==m_ics)
		if(1==pconnect->IScors())//server
		{ 
			if(getrequeststring()==tr("datefile_"))
			{
				Send_PageSQL_MultiEx(pconnect->GetUser(),pview,itype,"",sgetdate);
				Send_PageView_Multi(pconnect->GetUser(),pview,sgetdate);
			}
			else if(getrequeststring()==tr("list_"))
				Send_PageSQL_MultiEx(pconnect->GetUser(),pview,itype,"",sgetdate);
			else 
				Send_PageSQL_MultiEx(pconnect->GetUser(),pview,itype,"",sgetdate);
		}
	}
 
	removeurllist(qname);
}
void Dialog::PageImageFinish(const QString &qname ,int itype,BrowserWindow*pview)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname);
	ShowLog(pconnect,"PageFinish "+ qname);
	if(pconnect!=NULL)
	{  
		if(1==pconnect->IScors())//server
		{  
			//Send_PageSQL_MultiEx(pconnect->GetUser(),pview,itype,"",sgetdate);
			Send_PageView_Multi(pconnect->GetUser(),pview,sgetdate);
		}
	}

	removeurllist(qname);
}
void Dialog::PageSQLFinish_Local(const QString &qname,int itype,BrowserWindow*pview)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname);
	ShowLog(pconnect,"PageFinish "+ qname);

#ifdef CXVISIONBSERVER 
	//if(pconnect!=NULL)
	{  
		if(NULL==pview)
			pview = m_pageviewlist[0];

		if(NULL==pview)
			return;

		if(pview==m_pageviewlist[0])
			SetLoop(0,1);
		if(pview==m_pageviewlist[1])
			SetLoop(1,1);
		if(pview==m_pageviewlist[2])
			SetLoop(2,1);
		if(pview==m_pageviewlist[3])
			SetLoop(3,1);
			
		QString qpagelink =pview->GetFrameName();
		QString qstring ;
		
		qstring = tr("div|a+nav|a+div|a+td|a+h3|a+h2|a+h1|a+span|a+li|a+p|a+dd|a");
		
		QStringList qsplitlist = qstring.split("+");
		int isize = qsplitlist.size();
		QByteArray markup;
		markup.append(qpagelink+tr("\r\n"));
		for(int i=0;i<isize;i++)
		{
			QStringList qsplitlist2 = qsplitlist[i].split("|");
			if(qsplitlist2.size()>1)
			{
				QString stparser = qsplitlist2[0] + tr(" ") + qsplitlist2[1];
				markup.append(pview->ParserHtmlelementA(stparser));
			}
		} 		
		//////////////////////////////////////////////////////////////////////////
		QString strgetlist = markup;
		m_getlist = strgetlist.split("\r\n") ;
		if(m_sqlbrower!=0)
		{
			QString strpaserpage = m_getlist[0];
			
			m_getlist.pop_front();
			m_sqlbrower->AddRelationPage(strpaserpage);
			m_sqlbrower->AddPageStringList(m_getlist);
			if(strpaserpage!="")
			{
				ShowLog(0,tr("sqlx local list-> :")+strpaserpage+tr(" visit %1").arg(m_pagevisitnum));
				m_sqlbrower->cxsql_writepage(strpaserpage);
				m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,strpaserpage);
				m_sqlbrower->cxsql_setpagevalue("visit",tr("%1").arg(m_pagevisitnum)/*"3"*/,strpaserpage+tr("/"));
			}
		}
	}
#endif

//	removeurllist(qname);
}
void Dialog::DownloadFinish(const QString &qname)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname);
	//QByteArray *preqbuff =  getreqbuf(qname);
	//ShowLog(pconnect,"DEBUG: DownloadFinish 1"+ qname);
	//if(pconnect!=NULL)
	//ShowLog(pconnect,"DEBUG: DownloadFinish Pconnect ok");
	
	ShowLog(pconnect,"DownloadFinish:"+ qname);
	if(pconnect!=NULL)
	{
		if(geturlbuf(qname)->size()>0)
		{

			sethttpreqstring(*geturlbuf(qname));

			//Send_Request(pconnect,qname,*geturlbuf(qname));
			Send_Request_Multi(pconnect->GetUser(),qname,*geturlbuf(qname),sgetdate);
		}
	}
	else
	{ 
		sethttpreqtype(0);
		savefile((*geturlbuf(qname)),"temp.html"); 
		//if(m_localdutylist.size()>0)
		//	m_localdutylist.pop_front();
	}
	removeurllist(qname);
}
void Dialog::DownloadSQLFinish(const QString &qname,const QString &sdate)
{
	CxConnection *pconnect = geturlconnect(qname);
	QString sgetdate = geturldate(qname); 

	ShowLog(pconnect,"Download SQL Finish:"+ qname);
	if(pconnect!=NULL)
	{
		if(geturlbuf(qname)->size()>0)
		{

			sethttpreqstring(*geturlbuf(qname));

			//Send_Request(pconnect,qname,*geturlbuf(qname));
			Send_Request_Multi(pconnect->GetUser(),qname,*geturlbuf(qname),sdate);
		}
	}
	else
	{ 
		sethttpreqtype(0);
		savefile((*geturlbuf(qname)),"temp.html"); 
		//if(m_localdutylist.size()>0)
		//m_localdutylist.pop_front();
	}
	removeurllist(qname);
}
void Dialog::appendreqbuf(const QString &qstrurl,const QByteArray &buff)
{ 
	QByteArray *preqbuff = geturlbuf(qstrurl);
 
	preqbuff->append(buff);
}
void Dialog::GSearch(CxConnection*pconnect,int itype,const QString &qstrselect)
{
#ifdef CXVISIONBSERVER 

	//switch(itype)
	//{
	//case 0:
	//	m_pageviewlist[0]->SearchClear();
	//	break;
	//case 1:
	//	m_pageviewlist[0]->ParserHostEasyAll();
	//	m_pageviewlist[0]->SetParserOpt(6);
	//	m_pageviewlist[0]->TimerStart(true);
	//	break;
	//case 2:
	//	m_pageviewlist[0]->ParserPageMapExADD();
	//	m_pageviewlist[0]->SetParserOpt(7,qstrselect);
	//	m_pageviewlist[0]->TimerStart(true);

	//	break;
	//case 3:
	//	m_pageviewlist[0]->ParserPageMapExADD();
	//	m_pageviewlist[0]->SetParserOpt(0);
	//	m_pageviewlist[0]->TimerStart(true);

	//	break;
	//case 4:
	//	m_pageviewlist[0]->ParserPageMapExADD();
	//	m_pageviewlist[0]->SetParserOpt(0);
	//	m_pageviewlist[0]->TimerStart(true);

	//	break;

	//case 7:
	//	m_pageviewlist[0]->ParserPageMapExADD();

	//	break;
	//case 8:
	//	m_pageviewlist[0]->ParserHostEasyAll();

	//	break;

	//case 9: 
	//	m_pageviewlist[0]->TimerStart(false);
	//	break;
	//}

#endif
}
void Dialog::SetPosition(int x, int y, int w, int h)
{
	setGeometry( x, y, w, h);
}
void Dialog::SqlTimerRun()
{
	CxConnection *pconnect = GetActiveConnect();
	if(NULL==pconnect) 
	{
	//	ShowLog(NULL,"no active connect wait a loop");
		return;
	}
#ifdef CXVISIONBSERVER 
#ifndef TEMPTESTCXVISION
// -1 ?
// -2 wsql auto 
// -3 local wsql auto
// -3 wfile auto
// -5 wsqlc auto  -> content parser such as google search page content


	if(CanLoop(0)==1)
	{ 
		if(m_sqlbrower!=0)
		{ 
			if(m_pagesnum>0)
			{ 
				ShowLog(0,tr("sqlrun %1").arg(m_pagesnum) + m_strpage);
				int ivisit1 = 0;
				int ivisit2 = 0;
				switch(m_pagelevel)
				{
				case 0: 
					m_pagesnum = m_pagesnum + 1;
					//////////////////////////////////////////////////////////////////////////
					if(m_pagehost=="")
						m_strpage = m_sqlbrower->cxsql_getpagelevel(m_pagesnum,0);
					else
						m_strpage = m_sqlbrower->cxsql_getpagelevel_host(m_pagesnum,0,m_pagehost);
						
					ivisit1	= m_sqlbrower->cxsql_readpage("visit",m_strpage).toInt(); 
					
					ivisit2	= m_sqlbrower->cxsql_readpage("visit",m_strpage+"/").toInt(); 

					if(ivisit1< m_pagevisitnum /* 3 */
						&&ivisit2<m_pagevisitnum /* 3 */)
					{
						if(m_strpage!="")
						{ 
							SetLoop(0,0); 
							resqlrunTimer.restart();
							ShowLog(0,tr("sqlrunL0 %1:").arg(m_pagesnum)+m_strpage);
							QString strun1 = tr("wget ")+m_strpage;
							QString strun2 = tr("getsql"); 
							{
								AddDuty(pconnect,strun1); 
								AddDuty(pconnect,strun2); 
							} 
						}
					}
					//////////////////////////////////////////////////////////////////////////
					m_pagelevel = 1;
					break;
				case 1:
					//////////////////////////////////////////////////////////////////////////
					if(m_pagehost=="")
						m_strpage = m_sqlbrower->cxsql_getpagelevel(m_pagesnum,1);
					else
						m_strpage = m_sqlbrower->cxsql_getpagelevel_host(m_pagesnum,1,m_pagehost);
					//ShowLog(0,tr("sqlrun ")+m_strpage);
					ivisit1	= m_sqlbrower->cxsql_readpage("visit",m_strpage).toInt(); 
					ivisit2	=  m_sqlbrower->cxsql_readpage("visit",m_strpage+"/").toInt(); 

					if(ivisit1<m_pagevisitnum /* 3 */
						&&ivisit2<m_pagevisitnum /* 3 */)
					{
						if(m_strpage!="")
						{

							SetLoop(0,0); 
							resqlrunTimer.restart();
							ShowLog(0,tr("sqlrunL1 %1:").arg(m_pagesnum)+m_strpage);
							QString strun1 = tr("wget ")+m_strpage;
							QString strun2 = tr("getsql");

							{
								AddDuty(pconnect,strun1); 
								AddDuty(pconnect,strun2); 
							}

						}
					}
					//////////////////////////////////////////////////////////////////////////
					m_pagelevel = 2;
					break;
				case 2:
					////////////////////////////////////////////////////////////////////////////
					if(m_pagehost=="")
						m_strpage = m_sqlbrower->cxsql_getpagelevel(m_pagesnum,2);
					else
						m_strpage = m_sqlbrower->cxsql_getpagelevel_host(m_pagesnum,2,m_pagehost);
						
					ivisit1	= m_sqlbrower->cxsql_readpage("visit",m_strpage).toInt(); 
					ivisit2	=  m_sqlbrower->cxsql_readpage("visit",m_strpage+"/").toInt(); 

					if(ivisit1<m_pagevisitnum /* 3 */
						&&ivisit2<m_pagevisitnum /* 3 */)
					{
						if(m_strpage!="")
						{

							SetLoop(0,0); 
							resqlrunTimer.restart();
							ShowLog(0,tr("sqlrunL2 %1:").arg(m_pagesnum)+m_strpage);
							QString strun1 = tr("wget ")+m_strpage;
							QString strun2 = tr("getsql");

							{
								AddDuty(pconnect,strun1); 
								AddDuty(pconnect,strun2); 
							}

						}
					}
					////////////////////////////////////////////////////////////////////////////
					m_pagelevel = 0;
					break;
				case 3:
					m_pagelevel = 3;
					break;
				} 

			}
			else if(m_pagesnum==-1)
			{ 
				m_strpage = m_sqlbrower->cxsql_getpagequery();
				int ivisit1 = 0;
				int ivisit2 = 0;
				ivisit1	= m_sqlbrower->cxsql_readpage("visit",m_strpage).toInt(); 
				ivisit2	= m_sqlbrower->cxsql_readpage("visit",m_strpage+"/").toInt(); 


				ShowLog(0,tr("sqlquery  :")+m_strpage);

				if(ivisit1<m_pagevisitnum /* 3 */
					&&ivisit2<m_pagevisitnum /* 3 */)
				{
					if(m_strpage!="")
					{ 
						SetLoop(0,0); 
						resqlrunTimer.restart();
						QString strun1 = tr("wget ")+m_strpage;
						QString strun2 = tr("getsql"); 
						{
							AddDuty(pconnect,strun1); 
							AddDuty(pconnect,strun2); 
						} 
					}
				} 
			}
			else if(m_pagesnum==-2)
			{ 
				QString strpage = m_sqlbrower->cxsql_getStringquery();
				int ivisit1 = 0;
				int ivisit2 = 0;
				ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
				ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

				if(ivisit1<m_pagevisitnum /* 3 */
					&&ivisit2<m_pagevisitnum /* 3 */)
				{
					if(strpage!="")
					{ 
						//SetLoop(0,0); 
						resqlrunTimer.restart();
						QString strun1 = tr("wsql ")+strpage; 
						{
							//AddDuty(pconnect,strun1);  
							QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
							ShowLog(0,tr("sql wsql :")+strpage + tr("T:")+qstime);
							SetDateLoop(0,0,qstime,strpage);
							AddDuty_date(pconnect,strun1,qstime);
						} 
					}
				} 

			}
			else if(m_pagesnum==-3)// 
			{ 
				QString strpage = m_sqlbrower->cxsql_getStringquery(); 
				m_sqlbrower->setautogridsqlnum();
				int ivisit1 = 0;
				int ivisit2 = 0;
				ivisit1	= m_sqlbrower->cxsql_readstringpage("visit",strpage).toInt(); 
				ivisit2	= m_sqlbrower->cxsql_readstringpage("visit",strpage+"/").toInt(); 

				ShowLog(0,tr("sql local l0 query :")+strpage);

				if(ivisit1<m_pagevisitnum /* 3 */
					&&ivisit2<m_pagevisitnum /* 3 */)
				{
					if(strpage!="")
					{ 
						SetLoop(0,0); 
						resqlrunTimer.restart();
						if (m_view1time.elapsed() > 20*1000)
						{
							m_pageviewlist[0]->SetUsing(0);
						}
						if(!m_pageviewlist[0]->IsUsing())
						{
							m_view1time.restart();
							m_pageviewlist[0]->loadCxPagesql_local(strpage,tr("0"));
							return;
						}  
						
					}
				} 

			}
			else if(m_pagesnum==-4)
			{ 
				QString strpage = m_sqlbrower->cxsql_getStringquery();
				int ivisit1 = 0;
				int ivisit2 = 0;
				QString qsvisit1	= m_sqlbrower->cxsql_readpage("datestr",strpage) ; 
				ShowLog(0,tr("read string :")+strpage+tr(": ")+qsvisit1  );
				if(strpage!=""
				&&qsvisit1.size()<2)//need to set a val to make multi times download
				{ 
					resqlrunTimer.restart();
					QString strun1 = tr("wfile ")+strpage; 
					{
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql wfile :")+strpage + tr("T:")+qstime);
						SetDateLoop(0,0,qstime,strpage);
						AddDuty(pconnect,tr("req 10")); 
						AddDuty_date(pconnect,strun1,qstime);
 
					} 
				} 
  
			}
			else if(m_pagesnum==-5)
			{ 
				QString strpage = m_sqlbrower->cxsql_getStringquery();
				int ivisit1 = 0;
				int ivisit2 = 0;
				ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
				ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

				if(ivisit1<m_pagevisitnum /* 3 */
					&&ivisit2<m_pagevisitnum /* 3 */)
				{
					if(strpage!="")
					{ 
						//SetLoop(0,0); 
						resqlrunTimer.restart();
						QString strun1 = tr("wsqlc ")+strpage; 
						{
							//AddDuty(pconnect,strun1);  
							QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
							ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
							SetDateLoop(0,0,qstime,strpage);
							AddDuty_date(pconnect,strun1,qstime);
						} 
					}
				} 

			}
			else if(m_pagesnum==-6)//relationpage
			{ 
			
				QString strmethond;
				int isearchwebtype = m_sqlbrower->getsearchwebtype();
				if(1==isearchwebtype)
					strmethond = m_sqlbrower->cxsql_getColString_query(2);//wsqlc, wsql, wsql AND wsqlc
				QString strpage = m_sqlbrower->cxsql_getrelaton_query();
				ShowLog(0,tr("relationpage search web page  ") + strpage);
				ShowLog(0,tr("relationpage search web type %1").arg(isearchwebtype) );
				m_sqlbrower->setautogridsqlnum();
				switch(isearchwebtype)
				{
					case 1:		
						{	 
							if(strpage!="")
							{  
								resqlrunTimer.restart();
								QString strun1;
								if(strmethond=="wsqlc") 
									strun1 = tr("wsqlc ")+strpage; 
								else if(strmethond=="wsql")
									strun1 = tr("wsql ")+strpage; 
								else 
									strun1 = tr("wsqlc ")+strpage; 
								{
									//AddDuty(pconnect,strun1);  
									QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
									ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
									SetDateLoop(0,0,qstime,strpage);
									AddDuty_date(pconnect,strun1,qstime);
									//AddDuty(pconnect,strun1,qstime);
								} 
							}
  
						}
					break;
					case 0:
					{
						int ivisit1 = 0;
						int ivisit2 = 0;
						ivisit1	= m_sqlbrower->cxsql_read_relation_page("visit",strpage).toInt();  
						ShowLog(0,tr("relationpage search web ivisit1 %1").arg(ivisit1) );
						if(ivisit1<m_pagevisitnum  )
						{
							if(strpage!="")
							{ 
								//SetLoop(0,0); 
								resqlrunTimer.restart();
								QString strun1 = tr("wsql ")+strpage; 
								{
									//AddDuty(pconnect,strun1);  
									QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
									ShowLog(0,tr("sql wsql :")+strpage + tr("T:")+qstime);
									SetDateLoop(0,0,qstime,strpage);
									AddDuty_date(pconnect,strun1,qstime);
								} 
							}
						} 
					}
					break;
				
				}
			}
			else if(m_pagesnum==-7)//relationpage
			{ 

				QString strmethond;
				int isearchwebtype = m_sqlbrower->getsearchwebtype();
				if(1==isearchwebtype)
					strmethond = m_sqlbrower->cxsql_getColString_query(2);//wsqlc, wsql, wsql AND wsqlc
				QString strpage = m_sqlbrower->cxsql_getrelaton_query();
				ShowLog(0,tr("relationpage search web page  ") + strpage);
				ShowLog(0,tr("relationpage search web type %1").arg(isearchwebtype) );
				m_sqlbrower->setautogridsqlnum();
				switch(isearchwebtype)
				{
				case 1:		
					{	 
						if(strpage!="")
						{  
							resqlrunTimer.restart();
							QString strun1;
							if(strmethond=="wsqlc") 
								strun1 = tr("wsqlc ")+strpage; 
							else if(strmethond=="wsql")
								strun1 = tr("wsql ")+strpage; 
							else 
								strun1 = tr("wsqlc ")+strpage; 
							{
								//AddDuty(pconnect,strun1);  
								QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
								ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
								SetDateLoop(0,0,qstime,strpage);
								AddDuty_date(pconnect,strun1,qstime);
								//AddDuty(pconnect,strun1,qstime);
							} 
						}

					}
					break;
				case 0:
					{
						int ivisit1 = 0;
						int ivisit2 = 0;
						ivisit1	= m_sqlbrower->cxsql_read_relation_page("visit",strpage).toInt();  
						ShowLog(0,tr("relationpage search web ivisit1 %1").arg(ivisit1) );
						if(ivisit1<m_pagevisitnum  )
						{
							if(strpage!="")
							{ 
								//SetLoop(0,0); 
								resqlrunTimer.restart();
								QString strun1 = tr("wsql ")+strpage; 
								{
									//AddDuty(pconnect,strun1);  
									QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
									ShowLog(0,tr("sql wsql :")+strpage + tr("T:")+qstime);
									SetDateLoop(0,0,qstime,strpage);
									AddDuty_date(pconnect,strun1,qstime);
								} 
							}
						} 
					}
					break;

				}
			}
		}
	}
	else
	{
		if (resqlrunTimer.elapsed() > 40*1000)
		{  
			if(m_pagesnum==-3)
			{
				ShowLog(0,tr("reset sqlrun -3"));
				resqlrunTimer.restart();
				widgetList->clear();
				//Clear();
				SetLoop(0,1); 
			}
			else if(m_pagesnum==-4)
			{
				if (resqlrunTimer.elapsed() > 80*1000)
				{
					ShowLog(0,tr("reset sqlrun -4"));
					resqlrunTimer.restart();
					widgetList->clear();
					//Clear();
					SetLoop(0,1);  
				}
			}
			else if(m_pagesnum==-2)
			{
				ShowLog(0,tr("reset sqlrun CLoop 0"));
				resqlrunTimer.restart();
				widgetList->clear();
				 
				SetLoop(0,1);  
			}
			else if(m_pagesnum==-5)
			{
				ShowLog(0,tr("reset sqlrun CLoop 0"));
				resqlrunTimer.restart();
				widgetList->clear();

				SetLoop(0,1);  
			}
			else if(m_pagesnum==-6)
			{
				if (resqlrunTimer.elapsed() > 80*1000)
				{
					ShowLog(0,tr("reset sqlrun CLoop 0"));
					resqlrunTimer.restart();
					SetLoop(0,1);  
				}
			}
		}  
	}
	if(CanLoop(1)==1)
	{
		if(m_pagesnum==-2)// 
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();
 
			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{ 
					//SetLoop(0,0); 
					resqlrunTimer2.restart();
					QString strun1 = tr("wsql ")+strpage; 
					{
						//AddDuty(pconnect,strun1);  
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql query :")+strpage + tr("T:")+qstime);
						SetDateLoop(1,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);
						
					} 
				}
			} 

		}
		else if(m_pagesnum==-3)//local 
		{ 
			QString  strpage = m_sqlbrower->cxsql_getStringquery(); 
			m_sqlbrower->setautogridsqlnum();
			int ivisit1 = 0 ;
			int ivisit2 = 0 ;
			ivisit1	= m_sqlbrower->cxsql_readstringpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readstringpage("visit",strpage+"/").toInt(); 

			ShowLog(0,tr("sql local l1 query :")+strpage);

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{ 
					SetLoop(1,0); 
					resqlrunTimer2.restart();

					if (m_view2time.elapsed() > 20*1000)
					{
						m_pageviewlist[1]->SetUsing(0);
					} 

					if(!m_pageviewlist[1]->IsUsing())
					{
						m_view2time.restart();
						m_pageviewlist[1]->loadCxPagesql_local(strpage,tr("0"));
						return;
					}    
				}
			} 

		}
		else if(m_pagesnum==-5)// 
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();

			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{ 
					//SetLoop(0,0); 
					resqlrunTimer2.restart();
					QString strun1 = tr("wsqlc ")+strpage; 
					{
						//AddDuty(pconnect,strun1);  
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sqlc query :")+strpage + tr("T:")+qstime);
						SetDateLoop(1,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);

					} 
				}
			} 

		} 
		else if(m_pagesnum==-6)//relationpage
		{ 
			QString strmethond;
			int isearchwebtype = m_sqlbrower->getsearchwebtype();
			if(1==isearchwebtype)
				strmethond = m_sqlbrower->cxsql_getColString_query(2);//wsqlc, wsql, wsql AND wsqlc
			QString strpage = m_sqlbrower->cxsql_getrelaton_query();
			ShowLog(0,tr("relationpage search web page  ") + strpage);
			ShowLog(0,tr("relationpage search web type %1").arg(isearchwebtype) );
			m_sqlbrower->setautogridsqlnum();
			switch(isearchwebtype)
			{
			case 1:		
				{	 
					if(strpage!="")
					{  
						resqlrunTimer2.restart();
						QString strun1;
						if(strmethond=="wsqlc") 
							strun1 = tr("wsqlc ")+strpage; 
						else if(strmethond=="wsql")
							strun1 = tr("wsql ")+strpage; 
						else 
							strun1 = tr("wsqlc ")+strpage; 
						{
							//AddDuty(pconnect,strun1);  
							QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
							ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
							SetDateLoop(1,0,qstime,strpage);
							AddDuty_date(pconnect,strun1,qstime);
							//AddDuty(pconnect,strun1,qstime);
						} 
					}

				}
				break;
			case 0:
				{
					int ivisit1 = 0;
					int ivisit2 = 0;
					ivisit1	= m_sqlbrower->cxsql_read_relation_page("visit",strpage).toInt();  
					ShowLog(0,tr("relationpage search web ivisit1 %1").arg(ivisit1) );
					if(ivisit1<m_pagevisitnum  )
					{
						if(strpage!="")
						{ 
							//SetLoop(0,0); 
							resqlrunTimer2.restart();
							QString strun1 = tr("wsql ")+strpage; 
							{
								//AddDuty(pconnect,strun1);  
								QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
								ShowLog(0,tr("sql wsql :")+strpage + tr("T:")+qstime);
								SetDateLoop(1,0,qstime,strpage);
								AddDuty_date(pconnect,strun1,qstime);
							} 
						}
					} 
				}
				break;

			}
		}
	}
	else
	{
		if (resqlrunTimer2.elapsed() > 40*1000)
		{  
			if(m_pagesnum==-3)
			{
				ShowLog(0,tr("reset sqlrun reset -3 sqlrun CLoop 1"));
				resqlrunTimer2.restart();
				widgetList->clear();
				//Clear();
				SetLoop(1,1); 
			}
			else if(m_pagesnum==-2)
			{
				ShowLog(0,tr("reset sqlrun reset -2 sqlrun CLoop 1"));
				resqlrunTimer2.restart();
				widgetList->clear();
				 
				SetLoop(1,1);  
			}
			else if(m_pagesnum==-5)
			{
				ShowLog(0,tr("reset sqlrun reset -2 sqlrun CLoop 1"));
				resqlrunTimer2.restart();
				widgetList->clear();

				SetLoop(1,1);  
			}
			else if(m_pagesnum==-6)
			{
				if (resqlrunTimer2.elapsed() > 80*1000)
				{
					ShowLog(0,tr("reset sqlrun CLoop 1"));
					resqlrunTimer2.restart(); 
					SetLoop(1,1);  
				}
			}
		}
	}

	if(CanLoop(2)==1)
	{
		if(m_pagesnum==-2)// 
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();
			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{  
					resqlrunTimer3.restart();
					QString strun1 = tr("wsql ")+strpage; 
					{
						//AddDuty(pconnect,strun1);  
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql query :")+strpage + tr("T:")+qstime);
						SetDateLoop(2,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);
					} 
				}
			} 

		}
		else if(m_pagesnum==-3)//local 
		{ 
			QString  strpage = m_sqlbrower->cxsql_getStringquery(); 
			m_sqlbrower->setautogridsqlnum();
			int ivisit1 = 0 ;
			int ivisit2 = 0 ;
			ivisit1	= m_sqlbrower->cxsql_readstringpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readstringpage("visit",strpage+"/").toInt(); 

			ShowLog(0,tr("sql local l2 query :")+strpage);

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{ 
					SetLoop(2,0); 
					resqlrunTimer3.restart();

					if (m_view3time.elapsed() > 20*1000)
					{
						m_pageviewlist[2]->SetUsing(0);
					} 

					if(!m_pageviewlist[2]->IsUsing())
					{
						m_view3time.restart();
						m_pageviewlist[2]->loadCxPagesql_local(strpage,tr("0"));
						return;
					}    
				}
			} 

		}
		else if(m_pagesnum==-5)// 
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();
			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{  
					resqlrunTimer3.restart();
					QString strun1 = tr("wsqlc ")+strpage; 
					{
						//AddDuty(pconnect,strun1);  
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql query :")+strpage + tr("T:")+qstime);
						SetDateLoop(2,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);
					} 
				}
			} 

		}
		else if(m_pagesnum==-6)//relationpage
		{ 
			QString strmethond;
			int isearchwebtype = m_sqlbrower->getsearchwebtype();
			if(1==isearchwebtype)
				strmethond = m_sqlbrower->cxsql_getColString_query(2);//wsqlc, wsql, wsql AND wsqlc
			QString strpage = m_sqlbrower->cxsql_getrelaton_query();
			ShowLog(0,tr("relationpage search web page  ") + strpage);
			ShowLog(0,tr("relationpage search web type %1").arg(isearchwebtype) );
			m_sqlbrower->setautogridsqlnum();
			switch(isearchwebtype)
			{
			case 1:		
				{	 
					if(strpage!="")
					{  
						resqlrunTimer3.restart();
						QString strun1;
						if(strmethond=="wsqlc") 
							strun1 = tr("wsqlc ")+strpage; 
						else if(strmethond=="wsql")
							strun1 = tr("wsql ")+strpage; 
						else 
							strun1 = tr("wsqlc ")+strpage; 
						{
							//AddDuty(pconnect,strun1);  
							QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
							ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
							SetDateLoop(2,0,qstime,strpage);
							AddDuty_date(pconnect,strun1,qstime);
							//AddDuty(pconnect,strun1,qstime);
						} 
					}

				}
				break;
			case 0:
				{
					int ivisit1 = 0;
					int ivisit2 = 0;
					ivisit1	= m_sqlbrower->cxsql_read_relation_page("visit",strpage).toInt();  
					ShowLog(0,tr("relationpage search web ivisit1 %1").arg(ivisit1) );
					if(ivisit1<m_pagevisitnum  )
					{
						if(strpage!="")
						{ 
							//SetLoop(0,0); 
							resqlrunTimer3.restart();
							QString strun1 = tr("wsql ")+strpage; 
							{
								//AddDuty(pconnect,strun1);  
								QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
								ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
								SetDateLoop(2,0,qstime,strpage);
								AddDuty_date(pconnect,strun1,qstime);
							} 
						}
					} 
				}
				break;

			}
		}
	}
	else
	{
		if (resqlrunTimer3.elapsed() > 20*1000)
		{  
			if(m_pagesnum==-3)
			{
				ShowLog(0,tr("reset sqlrun -3 CLoop 2"));
				resqlrunTimer3.restart();
				widgetList->clear();
				//Clear();
				SetLoop(2,1); 
			}
			else if(m_pagesnum==-2)
			{
				ShowLog(0,tr("reset sqlrun CLoop 2"));
				resqlrunTimer3.restart();
				widgetList->clear();
				 
				SetLoop(2,1);  
			}
			else if(m_pagesnum==-5)
			{
				ShowLog(0,tr("reset sqlrun CLoop 2"));
				resqlrunTimer3.restart();
				widgetList->clear();

				SetLoop(2,1);  
			}	
			else if(m_pagesnum==-6)
			{
				if (resqlrunTimer3.elapsed() > 80*1000)
				{
					ShowLog(0,tr("reset sqlrun CLoop 2"));
					resqlrunTimer3.restart(); 
					SetLoop(2,1);  
				}
			}
		}	

	}

	if(CanLoop(3)==1)
	{ 
		if(m_pagesnum==-2)//
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();
			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{  
					resqlrunTimer4.restart();
					QString strun1 = tr("wsql ")+strpage; 
					{
						//AddDuty(pconnect,strun1);  
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql query :")+strpage + tr("T:")+qstime);
						SetDateLoop(3,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);
					} 
				}
			} 
		}
		else if(m_pagesnum==-3)//local 
		{ 
			QString  strpage = m_sqlbrower->cxsql_getStringquery(); 
			m_sqlbrower->setautogridsqlnum();
			int ivisit1 = 0 ;
			int ivisit2 = 0 ;
			ivisit1	= m_sqlbrower->cxsql_readstringpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readstringpage("visit",strpage+"/").toInt(); 

			ShowLog(0,tr("sql local l3 query :")+strpage);

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{ 
					SetLoop(3,0); 
					resqlrunTimer4.restart();

					if (m_view4time.elapsed() > 20*1000)
					{
						m_pageviewlist[3]->SetUsing(0);
					} 

					if(!m_pageviewlist[3]->IsUsing())
					{
						m_view4time.restart();
						m_pageviewlist[3]->loadCxPagesql_local(strpage,tr("0"));
						return;
					}    
				}
			} 

		}
		else if(m_pagesnum==-5)//
		{  
			QString strpage = m_sqlbrower->cxsql_getStringquery();
			int ivisit1 = 0;
			int ivisit2 = 0;
			ivisit1	= m_sqlbrower->cxsql_readpage("visit",strpage).toInt(); 
			ivisit2	= m_sqlbrower->cxsql_readpage("visit",strpage+"/").toInt(); 

			if(ivisit1<m_pagevisitnum /* 3 */
				&&ivisit2<m_pagevisitnum /* 3 */)
			{
				if(strpage!="")
				{  
					resqlrunTimer4.restart();
					QString strun1 = tr("wsqlc ")+strpage; 
					{
						QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
						ShowLog(0,tr("sql query :")+strpage + tr("T:")+qstime);
						SetDateLoop(3,0,qstime,strpage);
						AddDuty_date(pconnect,strun1,qstime);
					} 
				}
			} 
		}
		else if(m_pagesnum==-6)//relationpage
		{ 
			QString strmethond;
			int isearchwebtype = m_sqlbrower->getsearchwebtype();
			if(1==isearchwebtype)
				strmethond = m_sqlbrower->cxsql_getColString_query(2);//wsqlc, wsql, wsql AND wsqlc
			QString strpage = m_sqlbrower->cxsql_getrelaton_query();
 
			ShowLog(0,tr("relationpage search web page  ") + strpage);
			ShowLog(0,tr("relationpage search web type %1").arg(isearchwebtype) );
			m_sqlbrower->setautogridsqlnum();
			switch(isearchwebtype)
			{
			case 1:		
				{	 
					if(strpage!="")
					{  
						resqlrunTimer4.restart();
						QString strun1;
						if(strmethond=="wsqlc") 
							strun1 = tr("wsqlc ")+strpage; 
						else if(strmethond=="wsql")
							strun1 = tr("wsql ")+strpage; 
						else 
							strun1 = tr("wsqlc ")+strpage; 
						{
							//AddDuty(pconnect,strun1);  
							QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
							ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
							SetDateLoop(3,0,qstime,strpage);
							AddDuty_date(pconnect,strun1,qstime);
							//AddDuty(pconnect,strun1,qstime);
						} 
					}

				}
				break;
			case 0:
				{
					int ivisit1 = 0;
					int ivisit2 = 0;
					ivisit1	= m_sqlbrower->cxsql_read_relation_page("visit",strpage).toInt();  
					ShowLog(0,tr("relationpage search web ivisit1 %1").arg(ivisit1) );
					if(ivisit1<m_pagevisitnum  )
					{
						if(strpage!="")
						{ 
							resqlrunTimer4.restart();
							QString strun1 = tr("wsql ")+strpage; 
							{
								QString qstime = QTime::currentTime().toString(QLatin1String("0mmsszzz")); 
								ShowLog(0,tr("sql wsqlc :")+strpage + tr("T:")+qstime);
								SetDateLoop(3,0,qstime,strpage);
								AddDuty_date(pconnect,strun1,qstime);
							} 
						}
					} 
				}
				break;

			}
		}
	}
	else
	{
		if (resqlrunTimer4.elapsed() > 20*1000)
		{  
			if(m_pagesnum==-3)
			{
				ShowLog(0,tr("reset sqlrun -3 CLoop 3"));
				resqlrunTimer4.restart();
				widgetList->clear();
				//Clear();
				SetLoop(3,1); 
			}
			else if(m_pagesnum==-2)
			{
				ShowLog(0,tr("reset sqlrun CLoop 3"));
				resqlrunTimer4.restart();
				widgetList->clear();
				 
				SetLoop(3,1);  
			}
			else if(m_pagesnum==-5)
			{
				ShowLog(0,tr("reset sqlrun CLoop 3"));
				resqlrunTimer4.restart();
				widgetList->clear();

				SetLoop(3,1);  
			}
			else if(m_pagesnum==-6)
			{
				if (resqlrunTimer4.elapsed() > 80*1000)
				{
					ShowLog(0,tr("reset sqlrun CLoop 3"));
					resqlrunTimer4.restart(); 
					SetLoop(3,1);  
				}
			}
		}

	}

#endif 
#endif
}
void Dialog::setrequeststring(int itype)
{
	switch(itype)
	{
	default:
	case 0:
		m_reqstring =tr("page_");	
		break;
	case 1:
		m_reqstring =tr("file_");	
		break;
	case 10:
		m_reqstring =tr("datefile_");	
		break;
	case 2:
		m_reqstring =tr("image_");	
		break;
	case 3:
		m_reqstring =tr("list_");	
		break;
	case 4:
		m_reqstring =tr("imageframe_");	
		break;
	case 5:
		m_reqstring =tr("sql_");	
		break;
	}
}
void Dialog::SetCodeText(const QString &strcode)
{
    m_editor->setText(strcode);
}

void Dialog::Send_Picture(CxConnection*pconnect)
{
#ifdef CXVISIONBSERVER 
	if(pconnect!=NULL)
	{

		if(NULL==m_pageviewlist[0])
			return;
		QString qpagelink = m_pageviewlist[0]->GetFrameSize();
		QByteArray markup = m_pageviewlist[0]->GetFrameImage();
		QFileInfo qfileinf(qpagelink);
		QString qname = qfileinf.fileName();
		Send_Image(pconnect,qname,markup);
	}
	else
	{
		if(NULL==m_pageviewlist[0])
			return; 
		m_pageviewlist[0]->SaveFrameImage();
		//if(m_localdutylist.size()>0)
		//	m_localdutylist.pop_front();
	}
#endif
}
void Dialog::Send_Picture_Multi( const QString &user,BrowserWindow*pview,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 
	//if(pconnect!=NULL)
	{


		if(NULL==pview)
			pview =  m_pageviewlist[0];

		if(NULL==pview)
			return;
		QString qpagelink = pview->GetFrameSize();
		QByteArray markup = pview->GetFrameImage();
		QFileInfo qfileinf(qpagelink);
		QString qname = qfileinf.fileName();
		Send_Image_Multi(user, qname,markup);
	}
	//else
	//{
	//	if(NULL==m_pageview)
	//		return; 
	//	m_pageview->SaveFrameImage();
	//	//if(m_localdutylist.size()>0)
	//	//	m_localdutylist.pop_front();
	//}
#endif
}

void Dialog::Set_FrameView(int inum ,int isx,int isy,int ivw,int ivh)
{

#ifdef CXVISIONBSERVER  
	if(NULL==m_pageviewlist[inum])
		return;
	m_pageviewlist[inum]->SetFrameView(isx,isy,ivw,ivh);
#endif
}
void Dialog::Send_Page(CxConnection*pconnect)
{  
#ifdef CXVISIONBSERVER 
	if(NULL==m_pageviewlist[0])
		return;
	QString qpagelink = m_pageviewlist[0]->GetFrameName(); 
	QByteArray markup = m_pageviewlist[0]->GetFramePageHtml().toUtf8();//.toBase64();//
	//QFileInfo qfileinf(qpagelink);
	//QString qname = qfileinf.fileName();
	
	Send_Page(pconnect,qpagelink,markup);
#endif
}

void Dialog::Send_Page_Multi(const QString &user,BrowserWindow*pview ,const QString &qsdate)
{  
#ifdef CXVISIONBSERVER 

	if(NULL==pview)
		pview =  m_pageviewlist[0];

	if(NULL==pview)
		return;
	QString qpagelink = pview->GetFrameName(); 
	QByteArray markup = pview->GetFramePageHtml().toUtf8();//.toBase64();//
	//QFileInfo qfileinf(qpagelink);
	//QString qname = qfileinf.fileName();

	Send_Page_Multi(user,qpagelink,markup,qsdate);
#endif
}


void Dialog::Send_PageList(CxConnection*pconnect,int itype,const QString &qstrselect )
{
#ifdef CXVISIONBSERVER 
	
	if(NULL==m_pageviewlist[0])
		return;
	QString qpagelink = m_pageviewlist[0]->GetFrameName();
	QString qstring ;
	if(qstrselect==tr("")||qstrselect==tr(" "))
		qstring = tr("div|a+nav|a+div|a+td|a+h3|a+h2|a+h1|a+span|a+li|a+p|a+dd|a");
	else
		qstring = qstrselect;
	//ShowLog(0,qstring);
	QStringList qsplitlist = qstring.split("+");
	int isize = qsplitlist.size();
	QByteArray markup;
	
	for(int i=0;i<isize;i++)
	{
		QStringList qsplitlist2 = qsplitlist[i].split("|");
		if(qsplitlist2.size()>1)
		{
			QString stparser = qsplitlist2[0] + tr(" ") + qsplitlist2[1];
			markup.append(m_pageviewlist[0]->ParserHtmlelementA(stparser));
		}
	} 
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_List(pconnect,qname,markup);
#endif
}


void Dialog::Send_PageSQL_MultiEx(const QString &user,BrowserWindow*pview ,int itype,const QString &qstrselect,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 

	if(NULL==pview)
		pview =  m_pageviewlist[0];

	if(NULL==pview)
		return;
	QString qpagelink =pview->GetFrameName();
	QString qstring ;

	switch(itype)
	{
	default:
	case 0:
	case 1:

		if(qstrselect==tr("")||qstrselect==tr(" "))
			qstring = tr("div|a+nav|a+div|a+td|a+h3|a+h2|a+h1|a+span|a+li|a+p|a+dd|a");
		else
			qstring = qstrselect;
		break;
	case 2:

		if(qstrselect==tr("")||qstrselect==tr(" "))
			qstring = tr("cite");
		else
			qstring = qstrselect;
		break;
	}
		
		
		
		
//	ShowLog(0,qstring);
	QStringList qsplitlist = qstring.split("+");
	int isize = qsplitlist.size();
	QByteArray markup;
	
	markup.append(qpagelink+tr("\r\n"));
	for(int i=0;i<isize;i++)
	{
		
 
		switch(itype)
		{
			default:
			case 0:
			case 1:
				{
					QStringList qsplitlist2 = qsplitlist[i].split("|");
					if(qsplitlist2.size()>1)
					{
						QString stparser = qsplitlist2[0] + tr(" ") + qsplitlist2[1];
						markup.append(pview->ParserHtmlelementA(stparser));
					}
				}
			break;
			case 2:
				{
					QString stparser = qsplitlist[i];
					markup.append(pview->ParserHtmlelementContentA(stparser));
				}
			break;
		}
			
		 
	} 
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_SQL_MultiEx( user,qname,markup,qsdate);
#endif
}

void Dialog::Send_PageView_Multi( const QString &user,BrowserWindow*pview,const QString &qsdate)
{ 

	if(NULL==pview)
		pview =  m_pageviewlist[0];

	if(NULL==pview)
		return;

#ifdef CXVISIONBSERVER  
	//pview->slotViewFullScreen(true);
	QString qpagelink;// = GetViewSize(pview);
	QByteArray markup = GetViewImage(qpagelink,pview);
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();

	Send_ImageFrame_Multi(user, qname,markup,qsdate);
	
#endif
}

void Dialog::Send_PageSQL_Multi(const QString &user,int itypex,const QString &qstrselect ,BrowserWindow*pview,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 

	if(NULL==pview)
		pview =  m_pageviewlist[0];

	if(NULL==pview)
		return;
	QString qpagelink = pview->GetFrameName();
	QString qstring ;
	if(qstrselect==tr("")||qstrselect==tr(" "))
		qstring = tr("div|a+nav|a+div|a+td|a+h3|a+h2|a+h1|a+span|a+li|a+p|a+dd|a");
	else
		qstring = qstrselect;
	ShowLog(0,qstring);
	QStringList qsplitlist = qstring.split("+");
	int isize = qsplitlist.size();
	QByteArray markup;

	for(int i=0;i<isize;i++)
	{
		QStringList qsplitlist2 = qsplitlist[i].split("|");
		if(qsplitlist2.size()>1)
		{
			QString stparser = qsplitlist2[0] + tr(" ") + qsplitlist2[1];
		//	markup.append(qpagelink);
			markup.append(pview->ParserHtmlelementA(stparser));
		}
	} 
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_SQL_Multi( user,qname,markup);
#endif
}
void Dialog::Send_PageList_Multi(const QString &user,int itype,const QString &qstrselect ,BrowserWindow*pview ,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 

	if(NULL==pview)
		pview =  m_pageviewlist[0];

	if(NULL==pview)
		return;
	QString qpagelink = pview->GetFrameName();
	QString qstring ;
	if(qstrselect==tr("")||qstrselect==tr(" "))
		qstring = tr("div|a+nav|a+div|a+td|a+h3|a+h2|a+h1|a+span|a+li|a+p|a+dd|a");
	else
		qstring = qstrselect;
	ShowLog(0,qstring);
	QStringList qsplitlist = qstring.split("+");
	int isize = qsplitlist.size();
	QByteArray markup;

	for(int i=0;i<isize;i++)
	{
		QStringList qsplitlist2 = qsplitlist[i].split("|");
		if(qsplitlist2.size()>1)
		{
			QString stparser = qsplitlist2[0] + tr(" ") + qsplitlist2[1];
			markup.append(pview->ParserHtmlelementA(stparser));
		}
	} 
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_List_Multi( user,qname,markup);
#endif
}

void Dialog::C2C(CxConnection*pconnect,CxConnection*pconnect2)
{
    QString qsip4= pconnect->getio_peer_address_string();
	QStringList	alistparm  = qsip4.split(QLatin1String("."));	
	int ip1 =  alistparm.at(0).toInt();
	int ip2 =  alistparm.at(1).toInt();
	int ip3 =  alistparm.at(2).toInt();
	int ip4 =  alistparm.at(3).toInt();
    int iport =  pconnect->iopeerport();

    qsip4= pconnect->iopeerport();
	alistparm  = qsip4.split(QLatin1String("."));	
	int ip_1 =  alistparm.at(0).toInt();
	int ip_2 =  alistparm.at(1).toInt();
	int ip_3 =  alistparm.at(2).toInt();
	int ip_4 =  alistparm.at(3).toInt();
	
    int iport2 =  pconnect->iopeerport();

	pconnect->stoptimer();
	pconnect2->stoptimer();
 
	pconnect->sendpublicK(ip4,iport,ip_1,ip_4,iport2);
	pconnect2->sendpublicK(ip4,iport,ip_1,ip_4,iport2);
	//////////////////////////////////////////////////////////////////////////
	QString ipstring = tr("%1").arg(ip4)+ tr("%1").arg(ip_1)+tr("%1").arg(ip_4);
 
	ipstring = "U" + ipstring +"000000000";

	QString qstrtime = QTime::currentTime().toString("Chhmmsszzz");

	ipstring =  ipstring.mid(0,10)	+ qstrtime;	//("Uhhmmsszzz");//U123359375C123415656

	pconnect->SetUser(ipstring);//reset user
	pconnect2->SetUser(ipstring);//reset user
	ReFlashUSER();
	//////////////////////////////////////////////////////////////////////////
	pconnect->setattachconnect(pconnect2);
	pconnect2->setattachconnect(pconnect);
	pconnect->setstate(CxConnection::ConnectionState::P2Pconnection);
	pconnect2->setstate(CxConnection::ConnectionState::P2Pconnection);
}
void Dialog::U2U_connect(CxConnection*pconnect,const QString &quserb,const QString &csum)
{
	if(NULL==pconnect)
		return;  
	int isum  = csum.toInt();
	if(isum<=0)
		isum = 1;
	QString qusera =pconnect->GetUser();
	qusera = qusera.mid(0,10);////("Uhhmmsszzz");//U123359375C123415656

	int iuserasize =  GetUserConnectSize(qusera);
	int iuserbsize =  GetUserConnectSize(quserb);

 

	int iadda = isum - iuserasize ;
	int iaddb = isum - iuserbsize ;
	
	int iminsum = iuserasize>iuserbsize?iuserasize:iuserbsize;
	

	
	if(iadda>0)
	{
		CxConnection *p1 = GetUserConnect(qusera,0);
		if(p1!=NULL)
		p1->sendCommand(tr("new %1").arg(iadda));
		//AddUserConnect(qusera,iadda); 
		//pconnect->AddMsg("AVG Connecting");
		//return;
	}
	if(iaddb>0)
	{
		CxConnection *p2 = GetUserConnect(quserb,0);
		if(p2!=NULL)
		p2->sendCommand(tr("new %1").arg(iaddb));
		//AddUserConnect(quserb,iaddb);  	
		//pconnect->AddMsg("AVG Connecting");
		//return;
	}
	if(iaddb>0||iadda>0)
		return;
	else
	{
		for(int i=0;i<isum;i++)
		{
			CxConnection *p1 = GetUserConnect(qusera,i);
			CxConnection *p2 = GetUserConnect(quserb,i);

			if(p1!=NULL&&p2!=NULL)
			{
				C2C(p1,p2);
				removeconnect(p1);
                removeconnect(p2);
				CxConnectS aconnect;
				aconnect.m_pconnect = p1;
				aconnect.m_qsuser = qusera;
				m_P2Pconnections.push_back(aconnect);
 
				aconnect.m_pconnect = p2;
				aconnect.m_qsuser = quserb;
                m_P2Pconnections.push_back(aconnect);
			}
		}
		ReFlashUSER();
    }
}
void Dialog::P2P_connect(CxConnection*pconnect,const QString &qstring)
{
	if(NULL==pconnect)
		return; 
	CxConnection*pconnect2 = GetConnect(qstring );
	if(NULL==pconnect2)
		return;
		
    QString qsip4= pconnect->getio_peer_address_string();
	QStringList	alistparm  = qsip4.split(QLatin1String("."));	
	int ip1 =  alistparm.at(0).toInt();
	int ip2 =  alistparm.at(1).toInt();
	int ip3 =  alistparm.at(2).toInt();
	int ip4 =  alistparm.at(3).toInt();
    int iport =  pconnect->iopeerport();
	
    qsip4= pconnect->getio_peer_address_string();
	alistparm  = qsip4.split(QLatin1String("."));	
	int ip_1 =  alistparm.at(0).toInt();
	int ip_2 =  alistparm.at(1).toInt();
	int ip_3 =  alistparm.at(2).toInt();
	int ip_4 =  alistparm.at(3).toInt();
    int iport2 =  pconnect->iopeerport();
	
	 pconnect->stoptimer();
	 pconnect2->stoptimer();


	 pconnect->sendpublicK(ip4,iport,ip_1,ip_4,iport2);
	 pconnect2->sendpublicK(ip4,iport,ip_1,ip_4,iport2);
	 //////////////////////////////////////////////////////////////////////////
	 QString ipstring = tr("%1").arg(ip4)+ tr("%1").arg(ip_1)+tr("%1").arg(ip_4);

	 ipstring = "U" + ipstring +"000000000";

	 QString qstrtime = QTime::currentTime().toString("Chhmmsszzz");

	 ipstring =  ipstring.mid(0,10)	+ qstrtime;	//("Uhhmmsszzz");//U123359375C123415656

	 pconnect->SetUser(ipstring);//reset user
	 pconnect2->SetUser(ipstring);//reset user
	 ReFlashUSER();
	 //////////////////////////////////////////////////////////////////////////
	 pconnect->setattachconnect(pconnect2);
	 pconnect2->setattachconnect(pconnect);
	 pconnect->setstate(CxConnection::ConnectionState::P2Pconnection);
	 pconnect2->setstate(CxConnection::ConnectionState::P2Pconnection);
}
void Dialog::reset_connect(CxConnection*pconnect,const QString &qstring)
{
	if(NULL==pconnect)
		return;
 
	CxConnection*pconnect2 = GetConnect(qstring);
	if(NULL==pconnect2)
		return;
 
	pconnect2->overconnect(); 

}
void Dialog::reset_all()
{
	for(int i=0;i<m_connections.size();i++)
	{   
		 m_connections[i].m_pconnect->overconnect();
	}
	widgetList2->clear();
}
void Dialog::newserial()
{
    //CxConnection_serial *pconnection_serial = new CxConnection_serial(this);//serial
    //pconnection_serial->openSerialPort();
    //m_pconnection_serial = pconnection_serial;
}
void Dialog::senddirfile()
{
    const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
    QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"));
    if (dir.isEmpty())
        return;
    //m_pconnection_serial->senddir(dir);
}
void Dialog::sendserialfile(const char *pfile)
{
    //m_pconnection_serial->sendfile(pfile);//sendfilex
}
void Dialog::sendserialfile()
{
    QString fileName =
        QFileDialog::getOpenFileName(this, tr("Open File"),
        QDir::currentPath(),
        tr("ALL Files (*.*)"));
    if (fileName.isEmpty())
        return;
    //m_pconnection_serial->sendfile(fileName);

}
void Dialog::sendserialfilex()
{
    QString fileName =
        QFileDialog::getOpenFileName(this, tr("Open File"),
        QDir::currentPath(),
        tr("ALL Files (*.*)"));
    if (fileName.isEmpty())
        return;
   // m_pconnection_serial->sendfilex(fileName);//sendfilex

}

void Dialog::newconnect()
{
	QHostAddress qaddress;
 
	m_ptcpClient = new QTcpSocket;
	connect(m_ptcpClient, SIGNAL(connected()),this, SLOT(ClientIsConnection()));

	m_serverip =  GetInputText();
	if(m_serverip=="")
	{
        qaddress.setAddress(QLatin1String("192.168.1.2"));//192.168.1.2"));
        m_serverip = QLatin1String("192.168.1.2");//192.168.1.2");
    }
	else
		qaddress.setAddress(m_serverip);

    CxConnection *pconnection = new CxConnection(m_ptcpClient,this,0);//client 0

	if(m_serverport!="")
		pconnection->connectToHost(qaddress,m_serverport.toInt());
	else
	{
		m_serverport = tr("82");
		pconnection->connectToHost(qaddress,m_serverport.toInt());
	}
  
	const int Timeout = 10 * 1000;

	if (!m_ptcpClient->waitForConnected(Timeout)) 
	{
		pconnection->overconnect();
		ClientstartButton->setEnabled(true);
		clientStatusLabel->setText(tr("No Connected"));
		return; 
	}
	else
		pconnection->connectisok(m_connections.size());

}
void Dialog::newconnect_project()
{
    QHostAddress qaddress;

    m_ptcpClient = new QTcpSocket;
    connect(m_ptcpClient, SIGNAL(connected()),this, SLOT(ClientIsConnection()));

    m_serverip =  GetInputText();
    if(m_serverip=="")
    {
        qaddress.setAddress(QLatin1String("192.168.1.2"));//192.168.1.2"));
        m_serverip = QLatin1String("192.168.1.2");//192.168.1.2");
    }
    else
        qaddress.setAddress(m_serverip);
    QObject::connect(m_ptcpClient, SIGNAL(readyRead()), this, SLOT(ClientReadyRead_project()));

 //   CxConnection *pconnection = new CxConnection(m_ptcpClient,this,0);//client 0

    if(m_serverport!="")
        m_ptcpClient->connectToHost(qaddress,m_serverport.toInt());
    else
    {
        m_serverport = tr("82");
        m_ptcpClient->connectToHost(qaddress,m_serverport.toInt());
    }

    const int Timeout = 10 * 1000;

    if (!m_ptcpClient->waitForConnected(Timeout))
    {
        //pconnection->overconnect();
        ClientstartButton->setEnabled(true);
        clientStatusLabel->setText(tr("No Connected"));
        return;
    }
    else
    {
        //pconnection->connectisok(m_connections.size());'

    }
}


void Dialog::deleteconnect(const QString &qstconnect)
{
	CxConnection*pconnect = GetConnect(qstconnect); 
	removeconnect(pconnect);
}
void Dialog::new_connect(CxConnection*pconnect,const QString &quserstring)
{
	int isize = quserstring.toInt();
	for(int i=0;i<isize;i++)
		newconnect();
}

CxConnection*Dialog::GetConnect(const QString &qstring)
{
	QString getstr = qstring;
	
	for(int i=0;i<m_connections.size();i++)
	{  
        if(m_connections[i].m_pconnect->getio_peer_address_string()
                +tr(":%1").arg(m_connections[i].m_pconnect->iopeerport())
                ==getstr.remove(' '))
			return m_connections[i].m_pconnect;
	}
	return NULL;
}
void Dialog::removeconnect(CxConnection*pconnect)
{
	for(int i=0;i<m_connections.size();i++)
	{
		if(m_connections[i].m_pconnect==NULL)
			m_connections.removeAt(i);
		if(m_connections[i].m_pconnect==pconnect)
		{
			m_connections.removeAt(i);	
			//if(m_ics!= 0)
            //if(0==pconnect->IScors())//client
            //{//client
            //pconnect->deletesocket();
            //}
			ReFlashUSER();
			
			return;
		}
	}	
}
void Dialog::Send_ConnectList(CxConnection*pconnect)//server func
{ 
	for(int i=0;i<m_connections.size();i++)
	{  
        AddMsg(m_connections[i].m_pconnect->getio_peer_address_string()
               +tr(":%1").arg(m_connections[i].m_pconnect->iopeerport()),pconnect);
	} 
	//Send_List(pconnect,tr("connect"),arry);
}
int Dialog::GetUserConnectSize(const QString &quser)
{

	int isize = 0;
	for(int i=0;i<m_connections.size();i++)
	{  
		QString qsconuser =m_connections[i].m_pconnect->GetUser();

		qsconuser = qsconuser.mid(0,10);////("Uhhmmsszzz");//U123359375C123415656
		if(qsconuser==quser)
			isize = isize + 1;
	} 
	return isize;
}
void Dialog::AddUserConnect(const QString &quser,int isize)
{
	for(int i=0;i<m_connections.size();i++)
	{  
		QString qsconuser =m_connections[i].m_pconnect->GetUser();

		qsconuser = qsconuser.mid(0,10);////("Uhhmmsszzz");//U123359375C123415656
		if(qsconuser==quser)
		{
			if(isize>0)
				AddDuty_front(m_connections[i].m_pconnect,tr("new %1").arg(isize));		
			return;
		}
	} 
}
CxConnection* Dialog::GetUserConnect(const QString &quser,int inum)
{
	int igetnum  =0 ;
	for(int i=0;i<m_connections.size();i++)
	{  
		QString qsconuser =m_connections[i].m_pconnect->GetUser();

		qsconuser = qsconuser.mid(0,10);////("Uhhmmsszzz");//U123359375C123415656
		if(qsconuser==quser)
		{
			if(igetnum==inum)
				return m_connections[i].m_pconnect;
			igetnum = igetnum + 1;
		
		}
	} 
	return NULL;
}

CxConnection * Dialog::GetActiveConnect()
{  
	int igetnum  =0 ;
	for(int i=0;i<m_connections.size();i++)
	{  
		if(m_connections[i].m_pconnect!=NULL)
		{ 
			bool bisbusy =m_connections[i].m_pconnect->IsBusy();
			if(bisbusy==false)
			{
				return m_connections[i].m_pconnect;
			}
		}
	} 
	return NULL;
}
void Dialog::Send_UserList(CxConnection*pconnect)//server func
{ 

	QStringList userlist;
	for(int i=0;i<m_connections.size();i++)
	{  
		QString qsconuser =m_connections[i].m_pconnect->GetUser();
 
		qsconuser = qsconuser.mid(0,10);////("Uhhmmsszzz");//U123359375C123415656
		userlist<<qsconuser;
 	} 
 	userlist.removeDuplicates();

	for(int i=0;i<userlist.size();i++)
	{  
		AddMsg(userlist.at(i) ,pconnect);
	}
	//Send_List(pconnect,tr("connect"),arry);
}
void Dialog::Show_ConnectList()
{ 
	for(int i=0;i<m_connections.size();i++)
	{  
         ShowLog(0,m_connections[i].m_pconnect->getio_local_address_string()
                 +tr(":%1").arg(m_connections[i].m_pconnect->iolocalport())) ;
	} 
	//Send_List(pconnect,tr("connect"),arry);
}
void Dialog::Send_Desktop(CxConnection*pconnect,const QString &qmsg)
{ 
	QString qpagelink = GetDesktopSize();
	QByteArray markup = GetDesktopImage();
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_ImageFrame(pconnect,qname,markup);
	UseMouseKeyBoardMsg(qmsg);

}
void Dialog::Send_View(CxConnection*pconnect,const QString &qnum)
{ 

    BrowserWindow*pview = NULL;
	int inum =  qnum.toInt();
	if(inum<m_pageviewlist.size())
		pview  = m_pageviewlist[inum];
	else
		pview = m_pageviewlist[0];

	if(pview==NULL)	
		return;
	QString qpagelink;// = GetViewSize(pview);
	QByteArray markup = GetViewImage(qpagelink,pview);
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	Send_ImageFrame(pconnect,qname,markup);
//	UseMouseKeyBoardMsg(qmsg);

}

void Dialog::Send_Desktop_Multi( const QString &user,const QString &qmsg,const QString &qsdate)
{ 
	QString qpagelink = GetDesktopSize();
	QByteArray markup = GetDesktopImage();
    //QFileInfo qfileinf(qpagelink);
    QString qname = qpagelink;//qfileinf.fileName();
	Send_ImageFrame_Multi( user,qname,markup,qsdate);
    //UseMouseKeyBoardMsg(qmsg);

}
void Dialog::Send_Desktop_Multi_OneUser( const QString &qsdate)
{ 
	QString qpagelink = GetDesktopSize();
	QByteArray markup = GetDesktopImage();
    //QFileInfo qfileinf(qpagelink);
    QString qname =qpagelink;// qfileinf.fileName();
	Send_ImageFrame_Multi_OneUser( qname,markup,qsdate);
 

}
void Dialog::Send_View_Multi( const QString &user,const QString &qnum,const QString &qsdate)
{ 
    BrowserWindow*pview = NULL;
	int inum =  qnum.toInt();
	if(inum<m_pageviewlist.size())
		pview  = m_pageviewlist[inum];
	else
		pview = m_pageviewlist[0];
		
	if(pview==NULL)	
		return;

#ifdef CXVISIONBSERVER  
	pview->slotViewFullScreen(true);
	QString qpagelink;// = GetViewSize(pview);
	QByteArray markup = GetViewImage(qpagelink,pview);
	QFileInfo qfileinf(qpagelink);
	QString qname = qfileinf.fileName();
	
	Send_ImageFrame_Multi(user, qname,markup,qsdate);
	//UseMouseKeyBoardMsg(qmsg);
#endif
}
void Dialog::Send_MouseKeyBoardMsg_Multi(const QString &qmsg,const QString &qsdate)
{ 
 
	UseMouseKeyBoardMsg(qmsg);

}
void Dialog::setsendpiece(qint64 iID)
{
	m_datasendmap[iID] = true;
}
void Dialog::setfinishpiece(qint64 iID)
{
	m_datafinishmap[iID] = true;
}
qint64 Dialog::getsendpiece()
{
	QList<qint64> idmaplist = m_datafinishmap.keys();
	int imapsize = idmaplist.size();

	for(int i=0;i<imapsize;i++)
	{
		qint64 mapid = idmaplist[i];
		if(false==m_datafinishmap[mapid]
		&&false==m_datasendmap[mapid])
		{
			return mapid;
		}
	}
	return -1;
}
void Dialog::Add_Data(CxConnection*pconnect,int id)
{
    QFileInfo qfileinf(m_totaldatamap[id].m_stype);
	QString qname = qfileinf.fileName();  

	QDateTime now = QDateTime::currentDateTime();
	QString fileget = now.toString(QLatin1String("get_dd_hh_mm_ss"));

	CxPiece apiece;
	if(qname!=tr(""))
		apiece.qsname = qname ;
	else
		apiece.qsname = fileget;

    apiece.totallength = m_totaldatamap[id].m_data.size();//m_databuf.size();
	apiece.pieceLength = GetPieceSize();
	apiece.icurpiece = 0;
    apiece.pstringbuf = &m_totaldatamap[id].m_data;//&m_databuf;

    m_piecemap.insert(id,apiece);
    m_datafinishmap.insert(id,false);
    m_datasendmap.insert(id,false);

    CxPiece *pPiece = &m_piecemap[id];
	
	int isize  =  pPiece->totallength/pPiece->pieceLength + (pPiece->totallength%pPiece->pieceLength>0?1:0);
	 
	for(int i=0;i<isize;i++)
	{
		pPiece->m_ipiecestatus[i] = 0;
	}

    pPiece->m_user = pconnect->GetUser();
//	pconnect->AddData(pPiece);
}

void Dialog::Add_Data_Multi(const QString &user,int id,const QString &qsdate)
{
    QFileInfo qfileinf(m_totaldatamap[id].m_stype);
	QString qname = qfileinf.fileName();  

	QDateTime now = QDateTime::currentDateTime();
	QString fileget = now.toString(QLatin1String("get_dd_hh_mm_ss"));

	CxPiece apiece;
	if(qname!=tr(""))
		apiece.qsname = qname ;
	else
		apiece.qsname = fileget;

    apiece.totallength =m_totaldatamap[id].m_data.size();//m_databuf.size();
	apiece.pieceLength = GetPieceSize();
	apiece.icurpiece = 0;
	apiece.qsid = qsdate; //adata->m_qid;
    apiece.pstringbuf = &m_totaldatamap[id].m_data;//&m_databuf;

    m_piecemap.insert(id,apiece);
    m_datafinishmap.insert(id,false);
    m_datasendmap.insert(id,false);

    CxPiece *pPiece = &m_piecemap[id];

	int isize  =  pPiece->totallength/pPiece->pieceLength + (pPiece->totallength%pPiece->pieceLength>0?1:0);

	for(int i=0;i<isize;i++)
	{
		pPiece->m_ipiecestatus[i] = 0;
	}

    pPiece->m_user = user;
//	for(int i=0;i<m_connections.size();i++)
//	{
//		QString qsconuser =m_connections[i].m_pconnect->GetUser();
//        qsconuser = qsconuser.mid(0,10);
//		QString qsgetuser = user.mid(0,10);
//		if(qsconuser==qsgetuser)
//		{
//            m_connections[i].m_pconnect->AddData(pPiece);
//		}
//    }
}

void Dialog::Add_Data_Multi_OneUser(int id,const QString &qsdate)
{
    QFileInfo qfileinf(m_totaldatamap[id].m_stype);
	QString qname = qfileinf.fileName();  

	QDateTime now = QDateTime::currentDateTime();
	QString fileget = now.toString(QLatin1String("get_dd_hh_mm_ss"));

	CxPiece apiece;
	if(qname!=tr(""))
		apiece.qsname = qname ;
	else
		apiece.qsname = fileget;

    apiece.totallength = m_totaldatamap[id].m_data.size();//m_databuf.size();
	apiece.pieceLength = GetPieceSize();
	apiece.icurpiece = 0;
	apiece.qsid = qsdate; //adata->m_qid;
    apiece.pstringbuf = &m_totaldatamap[id].m_data;//&m_databuf;

    m_piecemap.insert(id,apiece);
    m_datafinishmap.insert(id,false);
    m_datasendmap.insert(id,false);

    CxPiece *pPiece = &m_piecemap[id];

	int isize  =  pPiece->totallength/pPiece->pieceLength + (pPiece->totallength%pPiece->pieceLength>0?1:0);

	for(int i=0;i<isize;i++)
	{
		pPiece->m_ipiecestatus[i] = 0;
	}

    pPiece->m_user = m_connections[0].m_pconnect->GetUser();
//	for(int i=0;i<m_connections.size();i++)
//    {
//        m_connections[i].m_pconnect->AddData(pPiece);
//	}
}

void Dialog::Send_File(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  

	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("file_") + qname;
	else
		adata.m_stype = tr("file_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pconnect,g_listID);

    AddSendReco(pconnect,tr(" "),qname);
	return;

}
void Dialog::SaveAutoCreate()
{

//    QString qstr = CommandEdit->text();

//    Send_Control_Multi(qstr);

    m_pmanager->saveautocreate();

     ShowLog(0,QString(tr("autosave ok")));
}
int Dialog::MapSize()
{
	return m_datafinishmap.keys().size();
}
void Dialog::ClearAll()
{
	QList<qint64> idmaplist = m_datafinishmap.keys();
	int imapsize = idmaplist.size();

	for(int i=0;i<imapsize;i++)
	{
		qint64 mapid = idmaplist[i];
		{
			ShowLog(0,tr("mapid = %1 remove").arg(mapid));
			m_totaldatamap[mapid].m_data.clear();
			m_totaldatamap[mapid].m_stype.clear();
			m_totaldatamap.remove(mapid);
			m_piecemap[mapid].m_ipiecestatus.clear();
			m_piecemap.remove(mapid);
			m_datafinishmap.remove(mapid);
			m_datasendmap.remove(mapid);

			removelist(0);
		}
	}
}
void Dialog::CollectionDataBufClear()
{

	QList<qint64> idmaplist = m_datafinishmap.keys();
	int imapsize = idmaplist.size();

	for(int i=0;i<imapsize;i++)
	{
		qint64 mapid = idmaplist[i];
		if(true==m_datafinishmap[mapid])
		{
			ShowLog(0,tr("mapid = %1 remove").arg(mapid));
			m_totaldatamap[mapid].m_data.clear();
			m_totaldatamap[mapid].m_stype.clear();
			m_totaldatamap.remove(mapid);
			m_piecemap[mapid].m_ipiecestatus.clear();
			m_piecemap.remove(mapid);
			m_datafinishmap.remove(mapid);
			m_datasendmap.remove(mapid);

			removelist(0);
		}
	}
}
bool Dialog::Send_TFile_Multi(const QString &fileName,const QByteArray &pagestr,int ifilenum,int iend,const QString &qsdate)
{
  //  CxConnection * pactconnect = GetActiveConnect();
  QString  user  = m_connections[0].m_pconnect->GetUser();

//if(0!=pactconnect)
//{
//    user = pactconnect->GetUser();
//   m_recorduser = user;
//}
//else
//{
//    return false;
//}

    QFileInfo qfileinf(fileName);
    QString qname = qfileinf.fileName();

    cxdata adata;

    if(qname!="")
        adata.m_stype = tr("Tfile_%1|%2|").arg(ifilenum).arg(iend) + qname;
    else
        adata.m_stype = tr("Tfile_%1|%2|").arg(ifilenum).arg(iend) + QTime::currentTime().toString(QLatin1String("hhmmss"));

    adata.m_data = pagestr;//m_databuf;
    adata.m_data = adata.m_data;// qCompress(adata.m_data);//

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user, g_listID ,qsdate);


    AddSendReco(NULL,tr(" "),qname);


    //widgetList->addItem(adata.m_stype);
    return true;


}
bool Dialog::Send_Control_Multi(const QString &pagestr, const QString &qsdate)
{
    CxConnection * pactconnect = GetActiveConnect();
    QString  user ;
if(0!=pactconnect)
{
   user = pactconnect->GetUser();
   m_recorduser = user;
}
else
{
    return false;
}

    cxdata adata;
    adata.m_stype = tr("Ctl_");
    adata.m_data = pagestr.toStdString().c_str();//m_databuf;
    adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pactconnect,g_listID);





    return true;
}

void Dialog::Get_ControlString(const QString &qname )
{
    int itolsize = m_piecefile.totallength;
    int ipsize =m_piecefile.pieceLength;

    if(itolsize==0
    ||ipsize==0)
        return;

    int ipiecenum = itolsize/ipsize + (itolsize%ipsize>0?1:0);
    m_databuf.clear();
    for(int i=0;i<ipiecenum;i++)
    {
        m_databuf += m_piecefile.m_qcontents[i];
    }

    m_piecefile.icurpiece = 0;
    m_piecefile.pieceLength = 0;
    m_piecefile.totallength = 0;
    m_piecefile.qsname = "";
    m_piecefile.qsid ="";
    m_piecefile.m_isfinish = 0;
    m_piecefile.m_qcontents.clear();
    m_piecefile.m_istatus.clear();

    m_databuf =  qUncompress(m_databuf);

    SetCodeText(m_databuf);
    TestParser();
}
int Dialog::Get_SaveTFileSend(const QString &qname, QByteArray &databuf)
{
   // QByteArray databuf = qUncompress(databuf0);
    QString qfilename ;
    int ifilenum;
    int iendnum;
    QStringList alist = qname.split("|");
    ifilenum = alist[0].toInt();
    iendnum = alist[1].toInt();
    qfilename = alist[2];

    QString qsavefilestring;
    if(m_savefiledir.isEmpty())
    {
        qsavefilestring = getlocationstringx("./file/"+qfilename);
    }
    else
    {
        qsavefilestring = m_savefiledir + qfilename;
    }

    ShowLog(0,tr(" ifilenum = %1").arg(ifilenum));

    int igetfilesize = m_getfiles.size();

    int ifindfile = 0;
    int ifindnum = -1;
    for(int ig =0;ig<igetfilesize;ig++)
    {
        if(m_getfiles[ig].m_filename == qsavefilestring)
        {
            ifindfile = 1;
            ifindnum = ig;
            if(0==m_getfiles[ig].m_istatus[ifilenum])
            {
                m_getfiles[ig].m_istatus[ifilenum] = 1;//get data
                m_getfiles[ig].m_getfilebytes[ifilenum] = databuf;
                m_getfiles[ig].m_bwrite[ifilenum] = false;
            }
        }
     }
    if(0==ifindfile)
    {
        CxGetFile acxgetfile;
        m_getfiles.push_back(acxgetfile);
        int isizex = m_getfiles.size();
        m_getfiles[isizex-1].m_filename = qsavefilestring;
        m_getfiles[isizex-1].m_istatus[ifilenum] = 1;
        m_getfiles[isizex-1].m_ifinish = 0;
        m_getfiles[isizex-1].m_ifinishsign = 0;
        m_getfiles[isizex-1].m_bwrite[ifilenum] = false;
        m_getfiles[isizex-1].m_getfilebytes[ifilenum] = databuf;
        m_getfiles[isizex-1].m_tfile = new QFile(qsavefilestring);

        ifindnum = isizex -1;

        if ( !m_getfiles[ifindnum].m_tfile->open(QFile::WriteOnly) )
        {
            ShowLog(0,tr("Tfile can't be open ")+qsavefilestring);

            return 0;

        }
        ShowLog(0,tr("Tfile file begin")+qsavefilestring);
        if(1==iendnum)
        {
            ShowLog(0,tr("Tfile file beg close ")+qsavefilestring);

            g_mutex.lock();
            m_getfiles[ifindnum].m_tfile->write(databuf);
            m_getfiles[ifindnum].m_getfilebytes[0].clear();
            m_getfiles[ifindnum].m_bwrite[0] = true;
            g_mutex.unlock();
            m_getfiles[ifindnum].m_tfile->close();
            delete m_getfiles[ifindnum].m_tfile;
            m_getfiles[ifindnum].m_tfile = 0;
            m_getfiles[ifindnum].m_ifinish = 1;
            m_getfilefinish = 1;
            return 1;
        }
    }
    if(-1!=ifindnum)
    if(1==iendnum)
    {
        m_getfiles[ifindnum].m_ifinishsign = ifilenum;
    }

    int ifindleak = -1;
    if(m_getfiles[ifindnum].m_ifinishsign>0
     &&1!=m_getfiles[ifindnum].m_ifinish)
    {
        ifindleak = 0;
        //check finish
        for(int i=0;i<=ifilenum;i++)
        {
            if(m_getfiles[ifindnum].m_istatus[i]==0)
            {
                ifindleak = 1;
            }
        }
     }

        int ifilesize = m_getfiles[ifindnum].m_istatus.size();
        for(int it=0;it<ifilesize;it++)
        {
            if(false ==m_getfiles[ifindnum].m_bwrite[it])
            {
                m_getfiles[ifindnum].m_bwrite[it] = true;
                g_mutex.lock();
                m_getfiles[ifindnum].m_tfile->write(m_getfiles[ifindnum].m_getfilebytes[it]);
                m_getfiles[ifindnum].m_getfilebytes[it].clear();
                g_mutex.unlock();
            }
        }

        if(1==iendnum)
        {
            if(0==ifindleak)
            {
                ShowLog(0,tr("Tfile file finish close")+qsavefilestring);
                m_getfiles[ifindnum].m_tfile->close();
                delete m_getfiles[ifindnum].m_tfile;
                m_getfiles[ifindnum].m_tfile = 0;

                m_getfiles[ifindnum].m_ifinish = 1;
                m_getfilefinish = 1;
                return 1;
            }
            ShowLog(0,tr("end no finish")+qsavefilestring);
            return 2;
        }

    if(0==ifindleak)
    {
        ShowLog(0,tr("Tfile file finishdata close!!!!")+qsavefilestring);
        m_tfile.close();
        m_getfiles[ifindnum].m_ifinish = 1;
        return 0;
    }

    ShowLog(0,tr("Tfile file end ")+qsavefilestring);

    return 0;
}

void Dialog::Send_File_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();

	cxdata adata;
	
	if(qname!="")
		adata.m_stype = tr("file_") + qname;
	else
		adata.m_stype = tr("file_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user,g_listID,qsdate);

	AddSendReco(NULL,tr(" "),qname);

    return;

}
void Dialog::Send_Page(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  

	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("page_") + qname;
	else
		adata.m_stype = tr("page_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pconnect,g_listID);



	AddSendReco(pconnect,tr(" "),qname);
    return;


}
void Dialog::Send_Page_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  

	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("page_") + qname;
	else
		adata.m_stype = tr("page_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user, g_listID,qsdate);

	AddSendReco(NULL,tr(" "),qname);

    return;


}
void Dialog::Send_List(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName(); 


	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("list_") + qname;
	else
		adata.m_stype = tr("list_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pconnect,g_listID);


    AddSendReco(pconnect,tr(" "),qname);
	return;
}
void Dialog::Send_List_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName(); 


	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("list_") + qname;
	else
		adata.m_stype = tr("list_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user,  g_listID,qsdate);

    AddSendReco(NULL,tr(" "),qname);
	return;


}
void Dialog::Send_SQL_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName(); 


	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("sql_") + qname;
	else
		adata.m_stype = tr("sql_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user,  g_listID,qsdate);


    AddSendReco(NULL,tr(" "),qname);
	return;


}
void Dialog::Send_SQL_MultiEx( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName(); 


	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("sqlx_") + qname;
	else
		adata.m_stype = tr("sqlx_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user,  g_listID,qsdate);

    AddSendReco(NULL,qsdate,qname);
	return;

}
void Dialog::Send_FileSQL_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  


	cxdata adata; 
	if(qname!="")
		adata.m_stype = tr("sqlf_") + qname;
	else
		adata.m_stype = tr("sqlf_") + QTime::currentTime().toString(QLatin1String("hhmmss"));

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user, g_listID,qsdate);

    AddSendReco(NULL,qsdate,qname);
	return;

}

void Dialog::Send_Image(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{
	QFileInfo qfileinf(fileName);

	cxdata adata; 

	adata.m_stype = tr("image_") + fileName;

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;


    Add_Data(pconnect,g_listID);

    AddSendReco(pconnect,tr(" "),fileName);
	return;


}


void Dialog::Send_Image_Multi(const QString &user, const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{
	cxdata adata; 

	adata.m_stype = tr("image_") + fileName;

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);

    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi( user, g_listID,qsdate);

	AddSendReco(NULL,tr(" "),fileName);

    return;
}

void Dialog::Send_ImageFrame(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{ 
	QFileInfo qfileinf(fileName);	

	cxdata adata; 

	adata.m_stype = tr("imageframe_") + fileName;

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pconnect,g_listID);
	AddSendReco(pconnect,tr(" "),fileName);

    return;


}

void Dialog::Send_ImageFrame_Multi_OneUser( const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{ 
	QFileInfo qfileinf(fileName);	

	cxdata adata; 

	adata.m_stype = tr("imageframe_") + fileName;

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi_OneUser( g_listID,qsdate);

	return;
}

void Dialog::Send_ImageFrame_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{ 
	QFileInfo qfileinf(fileName);	

	cxdata adata; 

	adata.m_stype = tr("imageframe_") + fileName;

	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user, g_listID,qsdate);

    AddSendReco(NULL,tr(" "),fileName);
	return;


}
void Dialog::Send_Request(CxConnection*pconnect,const QString &fileName,const QByteArray &pagestr)
{	
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  

	cxdata adata; 

	if(qname!="")
		adata.m_stype = m_reqstring + qname;
	else
		adata.m_stype = m_reqstring + QTime::currentTime().toString(QLatin1String("hhmmss"));


	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data(pconnect,g_listID);

    AddSendReco(pconnect,tr(" "),qname);
    return;
}

void Dialog::Send_Request_Multi( const QString &user,const QString &fileName,const QByteArray &pagestr,const QString &qsdate)
{	
	QFileInfo qfileinf(fileName);
	QString qname = qfileinf.fileName();  

	cxdata adata; 

	if(qname!="")
		adata.m_stype = m_reqstring + qname;
	else
		adata.m_stype = m_reqstring + QTime::currentTime().toString(QLatin1String("hhmmss"));


	adata.m_data = pagestr;//m_databuf;
	adata.m_data = qCompress(adata.m_data);
    g_listID = g_listID + 1;
    m_totaldatamap[g_listID] = adata;

    Add_Data_Multi(user, g_listID,qsdate);

    AddSendReco(NULL,tr(" "),qname);
	return;


}
void Dialog::SendLocalFile(CxConnection*pconnect,const QString &fileName)
{
	m_databuf.clear();
	m_databuf = loadfilestring(fileName);
	QFileInfo qfileinf(fileName);

	QString qname = qfileinf.fileName();
	Send_File(pconnect,qname,m_databuf);


}
void Dialog::SendLocalFile_Multi( const QString &user,const QString &fileName,const QString &qsdate)
{

	m_databuf.clear();
	m_databuf = loadfilestring(fileName);
	QFileInfo qfileinf(fileName);

	QString qname = qfileinf.fileName();
	Send_File_Multi( user, qname,m_databuf,qsdate);


}

void Dialog::removeurllist(const QString &qsurl)
{
	int inum = 0;
	int iurlistsize = m_urllist.size();
 
	for(int i=0;i<iurlistsize;i++)
	{
		if(qsurl==m_urllist[i].m_url)
		{

			m_urllist.removeAt(i);
 
			return;
		} 
	} 
 
}
CxConnection* Dialog::geturlconnect(const QString &qstring)
{
	int isize = m_urllist.size();
	for(int i= 0 ;i< isize ;i++)
	{
		if(m_urllist[i].m_url == qstring)
			return m_urllist[i].m_pconnect;
	}
	return NULL;
}
QString Dialog::geturldate(const QString &qstring) const
{
	int isize = m_urllist.size();
	for(int i= 0 ;i< isize ;i++)
	{
		if(m_urllist[i].m_url == qstring)
			return m_urllist[i].m_qsdate;
	}
	return "0";
}
QByteArray* Dialog::geturlbuf(const QString &qstring) 
{
	int isize = m_urllist.size();
	for(int i= 0 ;i< isize ;i++)
	{
		if(m_urllist[i].m_url == qstring)
			return &(m_urllist[i].m_buf);
	}
	return NULL;
}
CxConnection* Dialog::getdateconnnect(const QString &qstring)
{
	int isize = m_urllist.size();
	for(int i= 0 ;i< isize ;i++)
	{
		if(m_urllist[i].m_qsdate == qstring)
			return m_urllist[i].m_pconnect;
	}
	return NULL;
}
void Dialog::WGetPage(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER
	QUrl aurl(qstring); 
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);

	
	if(NULL==m_pageviewlist[0])
		return;
	//ShowLog(pconnect,"WGetPage DEBUG:"+acxurl.m_url);

	if (m_view1time.elapsed() > 20*1000)
	{
		m_pageviewlist[0]->SetUsing(0);
	}
	if (m_view2time.elapsed() > 20*1000)
	{
		m_pageviewlist[1]->SetUsing(0);
	}
	if (m_view3time.elapsed() > 20*1000)
	{
		m_pageviewlist[2]->SetUsing(0);
	}
	if (m_view4time.elapsed() > 20*1000)
	{
		m_pageviewlist[3]->SetUsing(0);
	}
 
	if(0==m_iviewuse)
	{
		m_iviewuse = 1;
		if(!m_pageviewlist[0]->IsUsing())
		{
			m_view1time.restart();
			m_pageviewlist[0]->loadCxPagesql(aurl.toString(),qsdate);

			return;
		}
	}
	if(1==m_iviewuse)
	{
		m_iviewuse = 2;
		if(!m_pageviewlist[1]->IsUsing())
		{
			m_view2time.restart();
			m_pageviewlist[1]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}
	if(2==m_iviewuse)
	{
		m_iviewuse = 3;
		if(!m_pageviewlist[2]->IsUsing())
		{
			m_view3time.restart();
			m_pageviewlist[2]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}
	if(3==m_iviewuse)
	{
		m_iviewuse = 0;
		if(!m_pageviewlist[3]->IsUsing())
		{
			m_view4time.restart();
			m_pageviewlist[3]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}
	m_pageviewlist[0]->loadCxPagesql(aurl.toString(),qsdate);

#endif
}
void Dialog::WSQLPage(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER
	QUrl aurl(qstring); 
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);


	if(NULL==m_pageviewlist[0])
		return;
	
	if (m_view1time.elapsed() > 20*1000)
	{
		m_pageviewlist[0]->SetUsing(0);
	}
	if (m_view2time.elapsed() > 20*1000)
	{
		m_pageviewlist[1]->SetUsing(0);
	}
	if (m_view3time.elapsed() > 20*1000)
	{
		m_pageviewlist[2]->SetUsing(0);
	}
	if (m_view4time.elapsed() > 20*1000)
	{
		m_pageviewlist[3]->SetUsing(0);
	}


	//ShowLog(pconnect,"WGetPage DEBUG date:"+qsdate);


	if(0==m_iviewuse)
	{
		m_iviewuse = 1;
		if(!m_pageviewlist[0]->IsUsing())
		{
			m_view1time.restart();
	//		ShowLog(pconnect,"WGetPage DEBUG veiw 1 run ");
			m_pageviewlist[0]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}

	if(1==m_iviewuse)
	{
		m_iviewuse = 2;
		if(!m_pageviewlist[1]->IsUsing())
		{
			m_view2time.restart();
	//		ShowLog(pconnect,"WGetPage DEBUG veiw 2 run ");
			m_pageviewlist[1]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}

	if(2==m_iviewuse)
	{
		m_iviewuse = 3;
		if(!m_pageviewlist[2]->IsUsing())
		{
			m_view3time.restart();
	//		ShowLog(pconnect,"WGetPage DEBUG veiw 3 run ");
			m_pageviewlist[2]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}

	if(3==m_iviewuse)
	{
		m_iviewuse = 0;
		if(!m_pageviewlist[3]->IsUsing())
		{
			m_view4time.restart();
	//		ShowLog(pconnect,"WGetPage DEBUG veiw 4 run ");
			m_pageviewlist[3]->loadCxPagesql(aurl.toString(),qsdate);
			return;
		}
	}

	m_iviewuse = 1;
//	ShowLog(pconnect,"WGetPage DEBUG End veiw 1 run ");
	m_view1time.restart();
	m_pageviewlist[0]->loadCxPagesql(aurl.toString(),qsdate);
	return;
	
#endif
}
void Dialog::WSQLPageC(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER
	QUrl aurl(qstring); 
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);


	if(NULL==m_pageviewlist[0])
		return;

	if (m_view1time.elapsed() > 20*1000)
	{
		m_pageviewlist[0]->SetUsing(0);
	}
	if (m_view2time.elapsed() > 20*1000)
	{
		m_pageviewlist[1]->SetUsing(0);
	}
	if (m_view3time.elapsed() > 20*1000)
	{
		m_pageviewlist[2]->SetUsing(0);
	}
	if (m_view4time.elapsed() > 20*1000)
	{
		m_pageviewlist[3]->SetUsing(0);
	}


	//ShowLog(pconnect,"WGetPage DEBUG date:"+qsdate);


	if(0==m_iviewuse)
	{
		m_iviewuse = 1;
		if(!m_pageviewlist[0]->IsUsing())
		{
			m_view1time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 1 run ");

			m_pageviewlist[0]->loadCxPagesqlc(aurl.toString(),qsdate);
			return;
		}
	}

	if(1==m_iviewuse)
	{
		m_iviewuse = 2;
		if(!m_pageviewlist[1]->IsUsing())
		{
			m_view2time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 2 run ");
			m_pageviewlist[1]->loadCxPagesqlc(aurl.toString(),qsdate);
			return;
		}
	}

	if(2==m_iviewuse)
	{
		m_iviewuse = 3;
		if(!m_pageviewlist[2]->IsUsing())
		{
			m_view3time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 3 run ");
			m_pageviewlist[2]->loadCxPagesqlc(aurl.toString(),qsdate);
			return;
		}
	}

	if(3==m_iviewuse)
	{
		m_iviewuse = 0;
		if(!m_pageviewlist[3]->IsUsing())
		{
			m_view4time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 4 run ");
			m_pageviewlist[3]->loadCxPagesqlc(aurl.toString(),qsdate);
			return;
		}
	}

	m_iviewuse = 1;
	//	ShowLog(pconnect,"WGetPage DEBUG End veiw 1 run ");
	m_view1time.restart();
	m_pageviewlist[0]->loadCxPagesql(aurl.toString(),qsdate);
	return;

#endif
}
#ifdef NEWADD
void Dialog::WImagePage(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER
	QUrl aurl(qstring); 
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);


	if(NULL==m_pageviewlist[0])
		return;

	if (m_view1time.elapsed() > 20*1000)
	{
		m_pageviewlist[0]->SetUsing(0);
	}
	if (m_view2time.elapsed() > 20*1000)
	{
		m_pageviewlist[1]->SetUsing(0);
	}
	if (m_view3time.elapsed() > 20*1000)
	{
		m_pageviewlist[2]->SetUsing(0);
	}
	if (m_view4time.elapsed() > 20*1000)
	{
		m_pageviewlist[3]->SetUsing(0);
	}


	//ShowLog(pconnect,"WGetPage DEBUG date:"+qsdate);


	if(0==m_iviewuse)
	{
		m_iviewuse = 1;
		if(!m_pageviewlist[0]->IsUsing())
		{
			m_view1time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 1 run ");
			m_pageviewlist[0]->loadCxPageImage(aurl.toString(),qsdate);
			return;
		}
	}
	else if(1==m_iviewuse)
	{
		m_iviewuse = 2;
		if(!m_pageviewlist[1]->IsUsing())
		{
			m_view2time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 2 run ");
			m_pageviewlist[1]->loadCxPageImage(aurl.toString(),qsdate);
			return;
		}
	}

	else if(2==m_iviewuse)
	{
		m_iviewuse = 3;
		if(!m_pageviewlist[2]->IsUsing())
		{
			m_view3time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 3 run ");
			m_pageviewlist[2]->loadCxPageImage(aurl.toString(),qsdate);
			return;
		}
	}

	else if(3==m_iviewuse)
	{
		m_iviewuse = 0;
		if(!m_pageviewlist[3]->IsUsing())
		{
			m_view4time.restart();
			//		ShowLog(pconnect,"WGetPage DEBUG veiw 4 run ");
			m_pageviewlist[3]->loadCxPageImage(aurl.toString(),qsdate);
			return;
		}
	}

	m_iviewuse = 1;
	//	ShowLog(pconnect,"WGetPage DEBUG End veiw 1 run ");
	m_view1time.restart();
	m_pageviewlist[0]->loadCxPageImage(aurl.toString(),qsdate);
	return;

#endif
}


#endif

void Dialog::WGetFile(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 

	QUrl aurl(qstring);
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);


	if(NULL==m_pageviewlist[0])
		return;  

	m_pageviewlist[0]->CxDownLoad(aurl.toString(),qsdate);
#endif
}
void Dialog::WSQLGetFile(CxConnection*pconnect,const QString &qstring,const QString &qsdate)
{
#ifdef CXVISIONBSERVER 

	QUrl aurl(qstring);
	cxurl acxurl;
	acxurl.m_pconnect = pconnect;
	acxurl.m_qsdate = qsdate;
	acxurl.m_url = aurl.toString();
	m_urllist.push_back(acxurl);
 

	if(NULL==m_pageviewlist[0])
		return;  
	
	m_pageviewlist[0]->CxDownLoadsql(aurl.toString(),qsdate);
#endif
}
void Dialog::ResetPro()
{

#ifdef CXVISIONBSERVER
	CurAppGolbalReset(); 
#endif
}
void Dialog::UpDatePro()
{  

#ifdef CXVISIONBSERVER
	CurAppGolbalUpData();
#endif
}

void Dialog::FileDir(CxConnection*pconnect,const QString &qsDir)
{
  
	const QDir cxDir(qsDir); 

	QStringList stfilterlist;

	QStringList filelist =  cxDir.entryList(QDir::AllEntries, QDir::Name);
	int isize = filelist.size();
	QString astr = "\r\n";
	for(int i=0;i<isize;i++)
	{
		astr += filelist.at(i); 
		astr += "\r\n";
 
	}
	pconnect->AddMsg(astr); 
}
void Dialog::AllShow(CxConnection*pconnect)
{
	QString qstrall;
	for(int i=0;i<m_textlist.size();i++)
	{
		qstrall = qstrall + m_textlist[i] + "\r\n";;
	}
	pconnect->AddMsg(qstrall); 
}
void Dialog::Clear()
{ 
	//m_pcurrentconnect->Clear();
	
	m_piecefile.icurpiece = 0;
	m_piecefile.pieceLength = 0;
	m_piecefile.totallength = 0;
	m_piecefile.qsname = "";
	m_piecefile.m_qcontents.clear();
	m_piecefile.m_istatus.clear();
	m_piecefile.qsid = ""; 
	m_piecefile.m_isfinish = 0;
	

	ShowLog(0,tr("Buff Clear"));
	clientProgressBar->reset();

}

void Dialog::Test1(int itype)
{ 
	if(0==itype)
	{
		QString fileName =
			QFileDialog::getOpenFileName(this, tr("Open File"),
			QDir::currentPath(),
			tr("ALL Files (*.*)"));
		if (fileName.isEmpty())
			return;

 
		QByteArray buf3 = qCompress(loadfilestring(fileName));

		QString fileName2 =
			QFileDialog::getSaveFileName(this, tr("Save File"),
			QDir::currentPath(),
			tr("ALL Files (*.*)"));
		QFile f(fileName2);

		if ( !f.open(QFile::WriteOnly) )
		{
			return;
		}

		f.write(buf3);
		f.close();
	
	}
	else
	{ 
		QString fileName =
			QFileDialog::getOpenFileName(this, tr("Open File"),
			QDir::currentPath(),
			tr("ALL Files (*.*)"));
		if (fileName.isEmpty())
			return;

 
		QByteArray buf3 = qUncompress(loadfilestring(fileName));

		QString fileName2 =
			QFileDialog::getSaveFileName(this, tr("Save File"),
			QDir::currentPath(),
			tr("ALL Files (*.*)"));
		QFile f(fileName2);

		if ( !f.open(QFile::WriteOnly) )
		{
			return;
		}

		f.write(buf3);
		f.close();
	}

}

void Dialog::SendMessage(CxConnection*pconnect,const QString &qstring)
{ 
	if(pconnect!=0)
		pconnect->sendMessage(qstring);
}
void Dialog::SendIrcMessage(const QString &qstring)
{ 
	CxConnection *pactconnect = GetActiveConnect();
	if(pactconnect!=0)
		pactconnect->sendMessage("<-[IRC]:"+qstring);

}

void Dialog::IrcOpt(CxConnection*pconnect,int iopt,const QString &qstring1,const QString &qstring2)
{

	CxConnection *phconnect= GetActiveConnect();
	if(NULL==phconnect)  
		SetActiveConnect(pconnect);
		
	switch(iopt)
	{
	case 0:
		if(qstring1!=""&&qstring2!="")
        {
#ifdef CXVISIONIRC
			QStringList alist = m_ircs.keys();
			if(false==alist.contains(qstring1))
			{
				m_pirc = new IrcClient(qstring1,qstring2);
				m_pirc->resize(300, 380);
				m_pirc->show();
				m_ircs[qstring1] = m_pirc ;
			} 
#endif
        }
        break;
	case 9:
		QStringList alist = m_ircs.keys();
		for(int i=0;i<alist.size();i++)
		{
			m_pirc = m_ircs[alist[i]];
			delete m_pirc;
			m_pirc = NULL;
        }
		break;
	}
}
void Dialog::IrcMsg(CxConnection*pconnect,const QString &qstring)
{ 
	//m_pcurrentconnect = pconnect;
	
	QString qircmsg = qstring.mid(7);
		
 
	int inulnum = 0;
	int isize = qircmsg.size();

	for(int i = 0;i<isize ;i++)
	{
		QChar achar = qircmsg.at(i);
		if(achar==' ')
		{
			inulnum = i;
			goto IRCMSGNEXT0;
		}
	}
	
	//////////////////////////////////////////////////////////////////////////
IRCMSGNEXT0:
	QString ircserver = qircmsg.mid(0,inulnum);
#ifdef CXVISIONIRC
	IrcClient*m_pirc = m_ircs[QString(ircserver)] ;
	if(m_pirc!=NULL)
		m_pirc->SendText(qircmsg.mid(inulnum+1));
#endif
	
}
QByteArray Dialog::GetDesktopImage()
{
    //QSize asize = QApplication::desktop()->size();
    m_image = QPixmap::grabWindow(QApplication::desktop()->winId()).toImage();

 	//m_image  = QPixmap::grabWindow(GetDesktopWindow(),0,0,asize.width(), asize.height()).toImage();
	/*QCursor aCursor;
	POINT curPos;
	GetCursorPos(&curPos);
	aCursor.setPos(curPos.x,curPos.y);
	aCursor.p*/
	m_image = m_image.convertToFormat(QImage::Format_RGB16);
	m_resultImage = m_image;
 	//////////////////////////////////////////////////////////////////////////
	//difference
	QPainter painter(&m_resultImage);
	painter.setCompositionMode(QPainter::CompositionMode_Source);
	painter.fillRect(m_resultImage.rect(), Qt::transparent);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	painter.drawImage(0, 0, m_image);
	painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
	painter.drawImage(0, 0, m_ioldimage);
	painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
	painter.fillRect(m_resultImage.rect(), Qt::white);
	painter.end();
 	//////////////////////////////////////////////////////////////////////////
 	m_ioldimage = m_image; 
 	QByteArray imagebits((char*)m_resultImage.bits(),m_resultImage.byteCount());
	return imagebits;
}
//////////////////////////////////////////////////////////////////////////
QString Dialog::GetDesktopSize()
{	
	QSize qsize;
	QDesktopWidget* desktop = QApplication::desktop();
 
	qsize = desktop->size();


//#ifdef CXVISIONBSERVER 
//#endif
	return tr("%1_").arg(qsize.width())+tr("%1").arg(qsize.height());
}

//////////////////////////////////////////////////////////////////////////
QByteArray Dialog::GetViewImage(QString&imagesize,BrowserWindow*pview)
{
#ifdef CXVISIONBSERVER 
	if(NULL==pview)
		pview =  m_pageviewlist[0];
 
	if(NULL==pview)
		return QByteArray("");

	//m_image  = QPixmap::grabWidget(pview,pview->frameGeometry()).toImage();
	int iw,ih;
	m_image  = pview->GetFrameQImage(iw,ih,pview->currentTab());

	imagesize = tr("%1_").arg(iw)+tr("%1").arg(ih);	
	
	ShowLog(0,imagesize);
#endif
	//////////////////////////////////////////////////////////////////////////
	m_image = m_image.convertToFormat(QImage::Format_RGB16);
	m_resultImage = m_image;
	//////////////////////////////////////////////////////////////////////////
	//difference
	QPainter painter(&m_resultImage);
	painter.setCompositionMode(QPainter::CompositionMode_Source);
	painter.fillRect(m_resultImage.rect(), Qt::transparent);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	painter.drawImage(0, 0, m_image);
	painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
	painter.drawImage(0, 0, m_ioldimage);
	painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
	painter.fillRect(m_resultImage.rect(), Qt::white);
	painter.end();
	//////////////////////////////////////////////////////////////////////////
	m_ioldimage = m_image; 
	QByteArray imagebits((char*)m_resultImage.bits(),m_resultImage.byteCount());
 
	return imagebits;

}


//////////////////////////////////////////////////////////////////////////
QString Dialog::GetViewSize(BrowserWindow*pview)
{	
	QRect qarea;
#ifdef CXVISIONBSERVER 


	//if(NULL==pview)
	//	pview =  m_pageviewlist[0];

	//if(NULL==pview)
	//	return tr("0_0"); 

	////qarea = pview->frameGeometry();

	//QWebFrame *frame ;
	//if(NULL!=pview)
	//	frame = pview->currentTab()->page()->mainFrame();
	//else
	//	frame =  currentTab()->page()->mainFrame();

	//int iw = frame->scrollBarMaximum( Qt::Orientation::Horizontal);//geometry();
	//int ih = frame->scrollBarMaximum( Qt::Orientation::Vertical);//geometry();
	
	int iw;int ih;
	return tr("%1_").arg(iw)+tr("%1").arg(ih);
	
#endif
	return tr("%1_").arg(qarea.width())+tr("%1").arg(qarea.height());
}
int asciiToKey(char ascii)
{
	switch ((unsigned char)ascii) 
	{
	case 'A': return 65;
	case 'B': return 66;
	case 'C': return 67;
	case 'D': return 68;
	case 'E': return 69;
	case 'F': return 70;
	case 'G': return 71;
	case 'H': return 72;
	case 'I': return 73;
	case 'J': return 74;
	case 'K': return 75;
	case 'L': return 76;
	case 'M': return 77;
	case 'N': return 78;
	case 'O': return 79;
	case 'P': return 80;
	case 'Q': return 81;
	case 'R': return 82;
	case 'S': return 83;
	case 'T': return 84;
	case 'U': return 85;
	case 'V': return 86;
	case 'W': return 87;
	case 'X': return 88;
	case 'Y': return 89;
	case 'Z': return 90;
	case '*': return 106;
	case '+': return 107;
	case '-': return 109;
	case '/': return 111;
	case '.': return 110; 
	case 'a': return 65;
	case 'b': return 66;
	case 'c': return 67;
	case 'd': return 68;
	case 'e': return 69;
	case 'f': return 70;
	case 'g': return 71;
	case 'h': return 72;
	case 'i': return 73;
	case 'j': return 74;
	case 'k': return 75;
	case 'l': return 76;
	case 'm': return 77;
	case 'n': return 78;
	case 'o': return 79;
	case 'p': return 80;
	case 'q': return 81;
	case 'r': return 82;
	case 's': return 83;
	case 't': return 84;
	case 'u': return 85;
	case 'v': return 86;
	case 'w': return 87;
	case 'x': return 88;
	case 'y': return 89;
	case 'z': return 90;
	
	
	default:   return ascii;
	}
}

void Dialog::SetKy(char akey)
{
#ifdef win32
	keybd_event(asciiToKey(akey),0,0,0);

	keybd_event(asciiToKey(akey),0,KEYEVENTF_KEYUP,0);
#endif
}
void Dialog::SetKy2(char akey1,char akey2)
{
#ifdef win32
	keybd_event(akey2,0,0,0);

	keybd_event(asciiToKey(akey1),0,0,0);
	
	keybd_event(asciiToKey(akey1),0,KEYEVENTF_KEYUP,0);

	keybd_event(akey2,0,KEYEVENTF_KEYUP,0);
#endif
}
void Dialog::SetKy3(char akey1,char akey2,char akey3)
{
#ifdef win32
	keybd_event(akey3,0,0,0);

	keybd_event(akey2,0,0,0);

	keybd_event(akey1,0,0,0);

	keybd_event(akey1,0,KEYEVENTF_KEYUP,0);
	keybd_event(akey2,0,KEYEVENTF_KEYUP,0);
	keybd_event(akey3,0,KEYEVENTF_KEYUP,0);
#endif
}
void Dialog::SetMouse(int imouseid,int ix,int iy)
{
#ifdef win32
	//MOUSEEVENTF_MOVE
	mouse_event(imouseid,ix,iy,0,0);
	QCursor acursor(Qt::CursorShape::ArrowCursor);
	acursor.setPos(ix,iy); 
	QDesktopWidget* desktop = QApplication::desktop();
	desktop->setCursor(acursor );
#endif
}
//////////////////////////////////////////////////////////////////////////
void Dialog::AddDuty(CxConnection*pconnect,const QString &qstring,const QString & qstime,int itype)
{
    QString qsdd = qstime;
    qint64 inum = Dialog::GetGolbalTime();
    if(qstime.toLongLong()>inum)
		qsdd = qstime;

	cxduty aduty;
	aduty.m_istats = 0;
	aduty.m_itype = itype;
	aduty.m_stime = qsdd;
	aduty.m_stcomm = qstring;

	pconnect->AddDuty(aduty);
	AddSendReco(pconnect,aduty.m_stime,qstring);
	
	//widgetList->addItem(tr("[%1 TYPE(%2)]:").arg(aduty.m_stime).arg(aduty.m_itype)+aduty.m_stcomm );

} 

void Dialog::AddDuty_date(CxConnection*pconnect,const QString &qstring,const QString & qstime,int itype)
{
    QString qsdd = qstime;

    qint64 inum = Dialog::GetGolbalTime();
    if(qstime.toLongLong()>inum)
        qsdd = qstime;

	cxduty aduty;
	aduty.m_istats = 0;
	aduty.m_itype = itype;
    aduty.m_stime = qsdd;
	aduty.m_stcomm = qstring;

	pconnect->AddDuty(aduty);
	AddSendReco(pconnect,aduty.m_stime,qstring);
 
} 
void Dialog::AddDuty_front(CxConnection*pconnect,const QString &qstring,const QString &qstime,int itype)
{
    QString qsdd = qstime;

    qint64 inum = Dialog::GetGolbalTime();
    if(qstime.toLongLong()>inum)
        qsdd = qstime;

	cxduty aduty;
	aduty.m_istats = 0;
	aduty.m_itype = itype;
	aduty.m_stime = qsdd;
	aduty.m_stcomm = qstring;

	pconnect->AddDuty_front(aduty);

	AddSendReco(pconnect,aduty.m_stime,qstring);
	
	//widgetList->addItem(tr("[%1 TYPE(%2)]:").arg(aduty.m_stime).arg(aduty.m_itype)+aduty.m_stcomm );

} 
void Dialog::AddLoacalDuty(const QString &qstring,int itype,const QString &qstime)
{
    QString qsdd = qstime;

    if(itype==-2)
    {
        //qint64 inum = Dialog::GetGolbalTime();
        //if(qstime.toLongLong()>inum)
        {
            qsdd = qstime;

            cxduty aduty;
            aduty.m_istats = 0;
            aduty.m_itype = -1;
            aduty.m_stime = qstime;//tr("%1").arg(inum);
            aduty.m_stcomm = qstring;
            m_localdutylist.push_back(aduty);
            widgetList3->addItem(tr("[%1 TYPE(%2)]:").arg(aduty.m_stime).arg(aduty.m_itype)+aduty.m_stcomm );

        }

    }
    else
    {
        //if(>inum)
        qsdd = qstime;

        cxduty aduty;
        aduty.m_istats = 0;
        aduty.m_itype = itype;
        aduty.m_stime = qstime;//tr("%1").arg(inum);
        aduty.m_stcomm = qstring;
        m_localdutylist.push_back(aduty);
        widgetList3->addItem(tr("[%1 TYPE(%2)]:").arg(aduty.m_stime).arg(aduty.m_itype)+aduty.m_stcomm );

    }
}

qint64 Dialog::GetGolbalTime()
{
    return m_sendTime.elapsed();
}
QStringList Dialog::CreateurlList(const QStringList &astrlist,const QUrl & qurl0)
{
    QStringList resultlist;
    QString strsch = qurl0.scheme();
    QString strhost = qurl0.host();
    QString strsec = qurl0.path();
    for(int i=0;i<astrlist.size();i++)
    {

        if(!astrlist[i].isEmpty())
        {
                QStringList qfiletypelist = astrlist[i].split(".");
                int iflistsize = qfiletypelist.size();
                QString qfiletype = qfiletypelist[iflistsize-1];


                    QUrl qurl(astrlist[i]);
                    QString qsch = qurl.scheme();
                    QString qhost = qurl.host();
                    QString strpage;
                    QString urlsec;
                    if(qhost.isEmpty()
                            ||qsch.isEmpty())
                    {
                        if(qhost.isEmpty())
                        {
                           qhost = strhost;
                        }
                        if(qsch.isEmpty())
                        {
                            qsch = strsch;
                        }
                        QStringList qsplitlist = strsec.split("/");
                        int ilistsize = qsplitlist.size();
                        QString qstrend = qsplitlist[ilistsize-1];
                        QString qremoveend("/");
                        if(!qstrend.isEmpty()
                                &&qstrend!="/")
                        {   
                            for(int ilz=0;ilz<ilistsize-1;ilz++)
                            {
                                qremoveend =qremoveend + qsplitlist[ilz] + "/";
                            }
                        }



                        if(qfiletype =="gz"
                                ||qfiletype =="xz"
                                ||qfiletype =="deb"
                                ||qfiletype =="zip"
                                ||qfiletype =="7z"
                                ||qfiletype =="bz2"
                                ||qfiletype =="pdf"
                                ||qfiletype =="rar"
                                ||qfiletype =="tgz"
                                )
                        {
                            strpage =tr("download ")+qsch+tr("://") + qhost + qremoveend + astrlist[i];
                        }
                        else
                        strpage =tr("url ")+qsch+tr("://") + qhost + qremoveend + astrlist[i];

                    }
                    else
                    {
                        if(qfiletype =="gz"
                                ||qfiletype =="xz"
                                ||qfiletype =="deb"
                                ||qfiletype =="zip"
                                ||qfiletype =="7z"
                                ||qfiletype =="bz2"
                                ||qfiletype =="pdf"
                                ||qfiletype =="rar"
                                ||qfiletype =="tgz"
                                )
                        strpage =tr("download ") + astrlist[i];
                        else
                        strpage =tr("url ") + astrlist[i];

                    }
                    if(!strpage.isEmpty())
                    resultlist.append(strpage);


            }

    }
    return resultlist;
}
void Dialog::AddTFileDuty(QString &strdownloadtfile)
{
    cxduty aduty;

    aduty.m_istats = 0;
    aduty.m_itype = -2;
    aduty.m_stime = tr(" ");//tr("%1").arg(inum);
    aduty.m_stcomm = strdownloadtfile;
    m_localdutylist.push_back(aduty);
    widgetList3->addItem(tr("[downloadtfile]").arg(aduty.m_stime)+aduty.m_stcomm );

}
void Dialog::CreateDateList(const QStringList &astrlist,qint64 ibegintime,qint64 igaptime)
{
    qint64 inum = Dialog::GetGolbalTime();

        QString strdate = tr("%1").arg(inum+ibegintime);
        QString strdate2 = tr("%1").arg(inum+ibegintime+igaptime);

        for(int i=0;i<astrlist.size();i++)
        {
            cxduty aduty;
            aduty.m_istats = 0;
            aduty.m_itype = -1;
            aduty.m_stime = strdate;//tr("%1").arg(inum);
            aduty.m_stcomm = astrlist[i];
            m_localdutylist.push_back(aduty);
            widgetList3->addItem(tr("[%1 TYPE(%1)]:").arg(aduty.m_stime)+aduty.m_stcomm );

            aduty.m_istats = 0;
            aduty.m_itype = -1;
            aduty.m_stime = strdate2;//tr("%1").arg(inum);
            aduty.m_stcomm = tr("mouse 1");
            m_localdutylist.push_back(aduty);
            widgetList3->addItem(tr("[%1 TYPE(%1)]:").arg(aduty.m_stime)+aduty.m_stcomm );

            aduty.m_istats = 0;
            aduty.m_itype = -1;
            aduty.m_stime = strdate2;//tr("%1").arg(inum);
            aduty.m_stcomm = tr("runopt run");
            m_localdutylist.push_back(aduty);
            widgetList3->addItem(tr("[%1 TYPE(%1)]:").arg(aduty.m_stime)+aduty.m_stcomm );

        }

}
void Dialog::CreateDateListX(const QStringList &astrlist,qint64 ibegintime,qint64 igaptime)
{

    qint64 inum = Dialog::GetGolbalTime();
    QString strdate = tr("%1").arg(inum+ibegintime);

    FILE * fp = 0;

    QString filename = getlocationstringx("./duty.txt");

    fp=fopen(filename.toStdString().c_str(),"at");


    for(int i=0;i<astrlist.size();i++)
    {

        cxduty aduty;

        aduty.m_istats = 0;
        aduty.m_itype = -1;
        aduty.m_stime = strdate;//tr("%1").arg(inum);
        aduty.m_stcomm = tr("url ")+astrlist[i];
        m_localdutylist.push_back(aduty);
        widgetList3->addItem(tr("[%1 TYPE(%1)]:").arg(aduty.m_stime)+aduty.m_stcomm );

        /////////////////////////////////
        /// \brief fp

        QString filestring = strdate + tr("|")+aduty.m_stcomm+tr("\r\n");
//        aduty.m_istats = 0;
//        aduty.m_itype = -1;
//        aduty.m_stime = strdate2;//tr("%1").arg(inum);
//        aduty.m_stcomm = tr("autotestparser");
//        m_localdutylist.push_back(aduty);
//        widgetList3->addItem(tr("[%1 TYPE(%1)]:").arg(aduty.m_stime)+aduty.m_stcomm );

//        QString filestring2 = strdate2 + tr("|")+aduty.m_stcomm+tr("\r\n");

            fprintf(fp,filestring.toStdString().c_str());
//            fprintf(fp,filestring2.toStdString().c_str());


    }
  fclose(fp);
}
void Dialog::AddMsg(const QString &qstring,CxConnection*pconnect)
{
	if(NULL!=pconnect)
		pconnect->AddMsg(qstring);
	else
		GetActiveConnect()->AddMsg(qstring);
	//widgetList->addItem(tr("MSG:")+qstring);
}
void Dialog::AddDutyNoReply(CxConnection*pconnect,const QString &qstring,const QString &qstrdate)
{ 
	QString qsdd;

    qint64 inum = Dialog::GetGolbalTime();
   if(qstrdate.toLongLong()>inum)
       qsdd = qstrdate;

	if(NULL!=pconnect)
		pconnect->sendCommand(qstring,qsdd);
} 
void Dialog::UseMouseKeyBoardMsg(const QString &qmsg)
{
	//QString qmsg = tr("EM%1_%2_%3")
	//QString qmsg = tr("EK")+event->key();
	QStringList	mkqslist  = qmsg.split("E");
	int ilistsize = mkqslist.size();
	for(int i=0;i<ilistsize;i++)
	{
		QString qstr = mkqslist[i];
		if(qstr.at(0)=='M')
		{
			qstr = qstr.mid(1);
			QStringList	mslist =qstr.split("_");
			int itype = mslist[0].toInt();
			int ix = mslist[1].toInt();
			int iy = mslist[2].toInt();
			SetMouse(itype,ix,iy);
			ShowLog(0,tr("mouse:")+qstr);
		}
		else if(qstr.at(0)=='K')
        {

			qstr = qstr.mid(1);
			QStringList	mslist =qstr.split("_");
			if(mslist.size()==2)
			{
                //int iget1 = mslist[0].toInt();
				int iget2 = mslist[1].toInt();
                char ichar1 = mslist[0].at(0).toLatin1();//(char) iget1;
				char ichar2 = iget2;//(char) iget2;
				SetKy2(ichar1,ichar2);
				
			}
			else 
			{ 
                char ichar1 = (char) qstr.at(0).toLatin1();//qstr.toInt();
				SetKy(ichar1);
			}
			ShowLog(0,tr("key:")+ qstr );
		}
	}
}
void Dialog::AppendText(const QString &strtext)
{ 
//debug
{
    if(ServerTextEdit->count()>1000)
        ServerTextEdit->clear();
    QStringList alist = strtext.split('\n');
    ServerTextEdit->addItems(alist);
    {
        if(alist.size()>0)
        {
            int is=alist.size();

            QDateTime now = QDateTime::currentDateTime();
            QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
            QString strfile = getlocationstringx("./log"+qyearmd+".txt");
            FILE *fp = fopen(strfile.toStdString().c_str(), "at");
            for(int it=0;it<is;it++)
            {
                fprintf(fp,(alist[it]+"\n\r").toStdString().c_str());
            }
            fclose(fp);
        }
    }
}
if(0)
{ 
	m_textlist.append(strtext);
	int isize = m_textlist.size();
	ServerTextEdit->clear();
 
	if(isize-30>0)
	{
		for(int i=isize-29;i<=isize-1;i++)
		{ 
            ServerTextEdit->addItem(m_textlist[i]);

		} 
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));
	}
	else
	{
		for(int i=0;i<=isize-1;i++)
		{ 
            ServerTextEdit->addItem(m_textlist[i]);
		} 
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));
	
	}
    if(isize>100)//20000
    {
		m_textlist.clear();
	}
 }
	
}

void Dialog::setwintext(QString qstr)
{
    serverStatusLabel->setText(qstr);

}
void Dialog::ShowLog(CxConnection*pconnect,const QString &qmsglog)
{
    if(nullptr!=pconnect)
	{
		QString connectname = pconnect->GetUser();

		CxConnection *phconnect= GetActiveConnect();
        if(nullptr==phconnect)
			SetActiveConnect(pconnect);

		
        AppendText(QTime::currentTime().toString("hh:mm:ss.zzz")+connectname +":"+qmsglog);

	}
	else
	{
        AppendText(QTime::currentTime().toString("hh:mm:ss.zzz") +":"+tr("Local:")+qmsglog);

	}
}
void Dialog::AddLog( const QString &qmsglog)
{
    int isize = m_textlist.size();
    m_textlist[isize-1] = m_textlist[isize-1] + qmsglog;
      isize = m_textlist.size();
    ServerTextEdit->clear();

    if(isize-30>0)
    {
        for(int i=isize-29;i<=isize-1;i++)
        {
            ServerTextEdit->addItem(m_textlist[i]);

        }
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));
    }
    else
    {
        for(int i=0;i<=isize-1;i++)
        {
            ServerTextEdit->addItem(m_textlist[i]);
        }
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));

    }
    if(isize>20000)
    {
        m_textlist.clear();
    }

}
void Dialog::SetLog( const QString &qmsglog)
{
    int isize = m_textlist.size();
    m_textlist[isize-1] = qmsglog;
      isize = m_textlist.size();
    ServerTextEdit->clear();

    if(isize-30>0)
    {
        for(int i=isize-29;i<=isize-1;i++)
        {
            ServerTextEdit->addItem(m_textlist[i]);

        }
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));
    }
    else
    {
        for(int i=0;i<=isize-1;i++)
        {
            ServerTextEdit->addItem(m_textlist[i]);
        }
        ServerTextEdit->addItem(tr(""));
        ServerTextEdit->addItem(tr(""));

    }
    if(isize>20000)
    {
        m_textlist.clear();
    }

}

void Dialog::ShowHttpLog(const QString &qmsglog)
{ 
	ShowLog(0, tr("HTTP:")+qmsglog);
}
void Dialog::removelist(int item)
 {
	int isize =  widgetList->count();
	if(isize>0)
	{
	 QListWidgetItem *pitem = widgetList->takeItem(0);

     if(pitem)
		 widgetList->removeItemWidget(pitem);
	}
 }
void Dialog::clearlist()
{
	widgetList->clear();
}
void Dialog::MKDir(const QString &astr)
{
	//QString qstrlocal = getlocationstringx(astr);
	const QDir cxDir(astr); 
	if (!cxDir.exists()) 
	{
		if (!cxDir.mkpath(astr)) 
		{
			return ;
		}
	} 
}
void Dialog::RMDir(const QString & astr)
{
	const QDir cxDir(astr); 
	if (!cxDir.exists()) 
	{
		if (!cxDir.rmpath(astr)) 
		{
			return ;
		}
	}  
}
void Dialog::cxCopyFile(const QString &stfloderorg,const QString &stflodersrc)
{ 
	QFile::copy(stfloderorg,stflodersrc);
} 
void Dialog::RemoveFile(const QString &stfileorg )
{ 
	QFile::remove(stfileorg);
}
void Dialog::RenameFile(const QString &strfileold,const QString &strfilenew)
{ 
	QFile::rename(strfileold , strfilenew);
}
bool Dialog::runWithQtInEnvironment(const QString &cmd)
{
	// prepend the qt binary directory to the path
	QStringList env = QProcess::systemEnvironment();
	for (int i=0; i<env.count(); ++i) {
		QString var = env.at(i);
		int setidx = var.indexOf(QLatin1Char('='));
		if (setidx != -1) {
			QString varname = var.left(setidx).trimmed().toUpper();
			if (varname == QLatin1String("PATH")) {
				var = var.mid(setidx + 1);
				var = QLatin1String("PATH=") + 
					QLibraryInfo::location(QLibraryInfo::BinariesPath) +
					QLatin1Char(';') + var;
				env[i] = var;
				break;
			}
		}
	}
	//for (int i=0; i<env.count(); ++i) 
	//{
	//ShowLog(NULL,tr("env =") + env[i]);
	//} 
	//ShowLog(NULL,tr("cmd =") + cmd);
	proc.setEnvironment(env);
	proc.start(cmd);
	//proc.waitForFinished(-1);

	return (proc.exitCode() == 0);
}



#ifdef CXVISIONBSERVER 
void Dialog::Sql_PageSave()
{
	QString qstr = tr("https://codeload.github.com/1/2/zip/master");
	QUrl qurl(qstr);
	QStringList strlist;
	QString urlsec = qurl.path();
	strlist.append(qurl.scheme());
	strlist.append(qurl.host());
	strlist.append( urlsec.split(QLatin1String("/")));
	if(m_sqlbrower!=NULL)
		m_sqlbrower->cxsql_add_pages(strlist);
}
#endif 
void Dialog::AddSendReco(CxConnection *pconnect,const QString &stime,const QString &qstr)//m_waitlist
{
	cxdutysend asend;
	asend.m_pconnectsend = pconnect;
	asend.m_stime = stime;
	asend.m_qstring = qstr;
	m_waitlist.push_back(asend);
	if(pconnect!=NULL)
		widgetList->addItem(pconnect->GetUser()+tr(" ")+ asend.m_stime+tr(" ")+qstr);
	else
		widgetList->addItem( tr("All User ")+ asend.m_stime+tr(" ")+qstr );
}

void Dialog::RemoveRecoT(const QString &stime)
{
	//ShowLog(NULL,tr("R removeT t=")+stime);
	 for(int i=0;i<m_waitlist.size();i++)
	 {
		if(m_waitlist[i].m_stime == stime)
		{
			//ShowLog(NULL,tr("debug R removeT t=")+stime);
			m_waitlist[i].m_pconnectsend->Reset();
			m_waitlist.removeAt(i);	
			removelist(i);
			return;
		}
	 }
	//{
	//	if(m_connections[i].m_pconnect==NULL)
	//		m_connections.removeAt(i);
	//	if(m_connections[i].m_pconnect==pconnect)
	//	{
	//		m_connections.removeAt(i);	
	//		if(m_ics!= 0)
	//		{//client
	//			pconnect->deletesocket();
	//		}
	//		ReFlashUSER();
	//		return;
	//	}
	//}
}
void Dialog::RemoveRecoN(const QString &sname)
{
	ShowLog(NULL,tr("R removeN n=")+sname);
	for(int i=0;i<m_waitlist.size();i++)
	{
		if(m_waitlist[i].m_qstring == sname)
		{
			m_waitlist.removeAt(i);	
			removelist(i);
			return;
		}
	}
	//{
	//	if(m_connections[i].m_pconnect==NULL)
	//		m_connections.removeAt(i);
	//	if(m_connections[i].m_pconnect==pconnect)
	//	{
	//		m_connections.removeAt(i);	
	//		if(m_ics!= 0)
	//		{//client
	//			pconnect->deletesocket();
	//		}
	//		ReFlashUSER();
	//		return;
	//	}
	//}
}

void Dialog::removepageview(int inum)
{
	if(inum<m_pageviewlist.size())
		m_pageviewlist.removeAt(inum);
}
void Dialog::desktopimage()
{
    m_image = QPixmap::grabWindow(QApplication::desktop()->winId()).toImage();
    m_pmanager->setimage(m_image);
}
void Dialog::desktopimagerect(int ix,int iy,int iw,int ih)
{
    m_image = QPixmap::grabWindow(QApplication::desktop()->winId(),ix,iy,iw,ih).toImage();
    m_pmanager->setimage(m_image);
}
void Dialog::setimage(QImage& imginput )
{
    m_pmanager->setimage(imginput);
}
void Dialog::setimagelist(QImage& imginput )
{
    m_pmanager->setimagelist(imginput);
}
void Dialog::setimageframe(QImage& imginput )
{
    m_pmanager->setimageframe(imginput);
}
void Dialog::pagelistwork(int igap1,int igap2)
{
    #ifdef BrowWin
    QStringList astrlist = m_pageviewlist[0]->getlist();
        m_pstringai->saveurltreelistcreate(astrlist);
         #endif
    //    CreateDateListX(astrlist,igap1,igap1);//+100s begin and gap 100
}
void Dialog::TcpIp2ComSendString(const char *pvarname)
{
    QString strget = m_pmanager->GetParserString(QString(pvarname));
    if(strget.isEmpty()!=true)
    {
       // if(m_pconnection_serial)
       //   m_pconnection_serial->sendstring(strget);
    }
}
bool Dialog::TcpIp2TcpIpSendImage(const char *pvarname)
{
    CxConnection * pactconnect = GetActiveConnect();
    QString  user ;
    if(0!=pactconnect)
    {
       user = pactconnect->GetUser();
       m_recorduser = user;
    }
    else
    {
        return false;
    }

    QImage *pimage = m_pmanager->GetParserImage(QString(pvarname));

    if(pimage==0)
        return true;

    QImage image = pimage->convertToFormat(QImage::Format_RGB16);

    QByteArray imagebits((char*)image.bits(),image.byteCount());

    QString qpagelink = tr("%1_").arg(image.width())+tr("%1").arg(image.height());

    QString qname = QString(qpagelink);

    Send_Image_Multi(user, qname,imagebits);

    return true;
}
bool Dialog::TcpIp2TcpIpSendValue(const char *pvarname)
{
    CxConnection * pactconnect = GetActiveConnect();
    QString  user ;
    if(0!=pactconnect)
    {
       user = pactconnect->GetUser();
       m_recorduser = user;
    }
    else
    {
        return false;
    }


    QString astrname(pvarname);
    double adouble = m_pmanager->GetParserValue(astrname);

    QString strdvalue = tr("%1").arg(adouble);

    QString strs= astrname + QString("_") +strdvalue;

    pactconnect->sendMessage(tr("value_")+strs);

    return true;
}
bool Dialog::TcpIp2TcpIpCompile(const char *pstring)
{
    CxConnection * pactconnect = GetActiveConnect();
    QString  user ;
    if(0!=pactconnect)
    {
       user = pactconnect->GetUser();
       m_recorduser = user;
    }
    else
    {
        return false;
    }


    QString astring(pstring);

    pactconnect->sendMessage(tr("compile ")+astring);

    return true;
}
void Dialog::TcpIp2ComSendImage(const char *pvarname)
{
    QImage *pimage = m_pmanager->GetParserImage(QString(pvarname));
    if(pimage!=0)
    {
      //  if(m_pconnection_serial)
       //     m_pconnection_serial->sendimage(*pimage);
    }
}
QString Dialog::getparservaluestring(QString astrname)
{
    double adouble = m_pmanager->GetParserValue(astrname);
    QString strdvalue = tr("%1").arg(adouble);
    return strdvalue;
}
void Dialog::TcpIp2ComSendValue(const char *parvarname)
{

    QString astrname(parvarname);
    double adouble = m_pmanager->GetParserValue(astrname);

    QString strdvalue = tr("%1").arg(adouble);
    // if(m_pconnection_serial)
     //   m_pconnection_serial->sendvalue(astrname,strdvalue);

}
void Dialog::GetComTcpIpDesktop()
{
    //if(m_pconnection_serial)
    //	m_pconnection_serial->sendCommand("A");
}
void Dialog::Com2TcpIpSendString(const char *pstr)
{
  //  if(m_pconnection_serial)
  //  {
  //      QString strsend = QString("B")+ pstr;
  //      m_pconnection_serial->sendCommand(strsend);
  //  }

}
void Dialog::runopt(const char *pname)
{
    m_pmanager->runoptcode(pname);
}
void Dialog::showmanagelog()
{
    ShowLog(0,m_pmanager->getoutputstring());
    m_pmanager->clearos();
}
void Dialog::updateview()
{
    m_pmanager->flashview();
}
void Dialog::flashview()
{
    m_pmanager->flashview();
}
void Dialog::mousegridmove()
{
    #ifdef BrowWin
    QPointF apoint =  m_pageviewlist[0]->currentTab()->page()->scrollPosition();
    m_pageviewlist[0]->currentTab()->setZoomFactor(1);
  //  int igrid = 5;
  //  if(0==m_pconsole)
  //      return;
  //  m_pconsole->mousemove(200,120);
  //  m_pconsole->click(1);
    QCoreApplication::processEvents();
   /* for(int iz = 0;iz < 110;iz++)
    {
        for(int iy=0;iy<5;iy++)
        {
           for (int ix=0;ix < 200;ix++)
            {
                m_pconsole->mousemove(ix*igrid,110+iy*2*igrid);
                QCoreApplication::processEvents();
            }
        }
        m_pconsole->key("Down");
        QCoreApplication::processEvents();

    }

    for(int iy=0;iy<100;iy++)
    {
       for (int ix=0;ix < 200;ix++)
        {
            m_pconsole->mousemove(ix*igrid,110+iy*2*igrid);
            QCoreApplication::processEvents();
        }
    }
 */
    m_pageviewlist[0]->showlist();
//m_pageviewlist[0]->Test();
//m_pconsole->click(qparm1.toInt());
    #endif
}
void Dialog::viewtimer(int itimes)
{
    if(itimes>0)
    {
        m_cxvisiontimer.start(itimes, this);
    }
    else
    {
        m_cxvisiontimer.stop();
    }
  //m_image = QPixmap::grabWindow(QApplication::desktop()->winId()).toImage();
  //WId
  //QWidget *qwidget = QWidget::find();
}
void Dialog::sceneScale(double newScale)
{
//    QMatrix oldMatrix = m_view->matrix();
//    m_view->resetMatrix();
//    m_view->translate(oldMatrix.dx(), oldMatrix.dy());
//    m_view->scale(newScale, newScale);
}

void Dialog::rundutylist()
{
    QString qrunstring = m_pstringai->runstep();
    if(qrunstring.isEmpty())
        return;
#ifdef BrowWin
    m_pageviewlist[0]->currentTab()->setUrl(qrunstring);
   if(0!=m_pdialogopt)
        m_pdialogopt->setcurstring(qrunstring.toStdString().c_str());
    m_pageviewlist[0]->setcollectionvalidnum();
    m_pageviewlist[0]->maketabviewone();
#endif
    widgetList3->clear();
    widgetList3->addItems(m_pstringai->prelist());
}
void Dialog::downloadlink(QString &qstr)
{
    for(int i=0;i<m_downloadlist.size();i++)
    {
        if(m_downloadlist[i]->IsFinish())
        {
           DownloadManager *padownload = m_downloadlist[i];
           delete padownload;
           m_downloadlist.removeAt(i);
        }
    }
    DownloadManager *pdownload = new DownloadManager(this);
    pdownload->append(qstr);
    //m_pdownload->append(qstr);
    m_downloadlist.push_back(pdownload);
}
void Dialog::cleartab()
{
#ifdef BrowWin
    m_pageviewlist[0]->maketabviewone();
#endif
}
void Dialog::showdebug(int ishow)
{
     visionmanager::g_showdebug=ishow;
}
void Dialog::showcustom(int ishow)
{
     visionmanager::g_showcustom=ishow;
}

void Dialog::clearfilter()
{
    m_pstringai->clearfilter();
}
void Dialog::addextfilter(const QString &str)
{
    m_pstringai->addextfilter(str.toStdString().c_str());
}
//void Dialog::RunAIString()
//{
//    QString qstr =  m_pstringai->getstring(0);
//    runopt(qstr.toStdString().c_str());
//}
void Dialog::addkeywordfilter(const QString &str)
{
    m_pstringai->addkeywordfilter(str.toStdString().c_str());
}
void Dialog::addneedstringlist(const QString &str)
{
    m_pstringai->addneedstringlist(str.toStdString().c_str());
}
void Dialog::runstringai()
{//easy ai
    QString qstr = m_pstringai->getstring(-1);
    QString qopt = m_pstringai->cxvisionaiparserstring("cxvisionai",qstr);
    ShowLog(0,"cxvisionai run:"+qopt);
    runopt(qopt.toStdString().c_str());
}
//! [6]

//! [7]
VisionTab::VisionTab(visionView*pview, QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(pview);
    mainLayout->addStretch(1);
    setLayout(mainLayout);
}
//! [7]
SpectrumTab::SpectrumTab(SpectrumWidget*pview1,SpectrumWidget*pview2, QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
//    mainLayout->addWidget(pview1);
//    mainLayout->addWidget(pview2);
//    mainLayout->addStretch(1);
//    setLayout(mainLayout);
}



    dialogOPT::dialogOPT():
        m_pdialog(nullptr),
        m_plc_input(nullptr),
        m_plc_output(nullptr),
        m_master_input(nullptr),
        m_master_output(nullptr),
       m_serialportslave(nullptr),
       m_modbustcpi1(nullptr),
       m_modbustcpi2(nullptr),
       m_modbustcpi3(nullptr),
       m_modbustcpw1(nullptr),
       m_modbustcpw2(nullptr),
       m_modbustcpw3(nullptr)
    {}
    dialogOPT::~dialogOPT()
    {

        if(nullptr!=m_plc_input)
        {
            delete m_plc_input;
            m_plc_input=nullptr;
        }
        if(nullptr!=m_plc_output)
        {
            delete m_plc_output;
            m_plc_output=nullptr;
        }
        if(nullptr!=m_serialportslave)
        {
            delete m_serialportslave;
            m_serialportslave=nullptr;
         }
    }

    void dialogOPT::setdialog(Dialog *pdialog)
    {
        m_pdialog = pdialog;

        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_serialportslave)
        {
            m_serialportslave->setdialog(m_pdialog);
        }
    }
    void dialogOPT::release()
    {

        if(nullptr!=m_plc_input)
        {
            delete m_plc_input;
            m_plc_input=nullptr;
        }
        if(nullptr!=m_plc_output)
        {
            delete m_plc_output;
            m_plc_output=nullptr;
        }
        if(nullptr!=m_serialportslave)
        {
            delete m_serialportslave;
            m_serialportslave=nullptr;
         }

    }


    void dialogOPT::setstyle(int istyle)
    {
        const QStringList styleKeys = QStyleFactory::keys();
        int inum = 0;
        for (const QString &styleName : styleKeys)
        {
            if(istyle==inum)
            {
                QStyle *style = QStyleFactory::create(styleName);
                QApplication::setStyle(style);
                return;
            }
            inum++;
        }
        QApplication::setStyle(new NorwegianWoodStyle);
    }

    void dialogOPT::viewtimer(int itimes)
    {
        if(nullptr!=m_pdialog)
        {
            m_pdialog->viewtimer(itimes);
        }
    }
    void dialogOPT::download(const char*pchar)
    {
        QString astr(pchar);
        if(nullptr!=m_pdialog)
            m_pdialog->downloadlink(astr);

        //m_pdownload->append(astr);
    }
    void dialogOPT::downloadA()
    {
        //QStringList astrlist;
        //astrlist.append(m_curstr);
        //m_pdownload->append(astrlist);
        if(nullptr!=m_pdialog)
            m_pdialog->downloadlink(m_curstr);

    }
    void dialogOPT::runviewparser(const char*pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->viewparserlist(pchar);
    }
    void dialogOPT::runjavascript(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->viewrunjavascript(pchar);
    }
    void dialogOPT::setgaptime(int igaptime)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->setgaptime(igaptime);
    }
    void dialogOPT::getcomtcpipdesktop()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->GetComTcpIpDesktop();
    }

    QString dialogOPT::inputstring(const char pchar)
    {
        if(QString(pchar)==" "){return QString("space") ;}
        else if(QString(pchar)=="!"){return QString("exclam");}
        else if(QString(pchar)=="\""){return QString("quotedbl");}
        else if(QString(pchar)=="#"){return QString("numbersign");}
        else if(QString(pchar)=="$"){return QString("dollar") ;}
        else if(QString(pchar)=="%"){return QString("percent") ;}
        else if(QString(pchar)=="&"){return QString("ampersand");}
        else if(QString(pchar)=="'"){return QString("apostrophe");}
        else if(QString(pchar)=="'"){return QString("quoteright")  ;}
        else if(QString(pchar)=="("){return QString("parenleft");}
        else if(QString(pchar)==")"){return QString("parenright")  ;}
        else if(QString(pchar)=="*"){return QString("asterisk");}
        else if(QString(pchar)=="+"){return QString("plus") ;}
        else if(QString(pchar)==","){return QString("comma") ;}
        else if(QString(pchar)=="-"){return QString("minus") ;}
        else if(QString(pchar)=="."){return QString("period");}
        else if(QString(pchar)=="/"){return QString("slash");}
        else if(QString(pchar)=="0"){return QString("0");}
        else if(QString(pchar)=="1"){return QString("1");}
        else if(QString(pchar)=="2"){return QString("2");}
        else if(QString(pchar)=="3"){return QString("3");}
        else if(QString(pchar)=="4"){return QString("4");}
        else if(QString(pchar)=="5"){return QString("5");}
        else if(QString(pchar)=="6"){return QString("6");}
        else if(QString(pchar)=="7"){return QString("7");}
        else if(QString(pchar)=="8"){return QString("8");}
        else if(QString(pchar)=="9"){return QString("9");}
        else if(QString(pchar)==":"){return QString("colon");}
        else if(QString(pchar)==";"){return QString("semicolon");}
        else if(QString(pchar)=="<"){return QString("less");}
        else if(QString(pchar)=="="){return QString("equal");}
        else if(QString(pchar)==">"){return QString("greater");}
        else if(QString(pchar)=="?"){return QString("question");}
        else if(QString(pchar)=="@"){return QString("at");}
        else if(QString(pchar)=="A"){return QString("A");}
        else if(QString(pchar)=="B"){return QString("B");}
        else if(QString(pchar)=="C"){return QString("C");}
        else if(QString(pchar)=="D"){return QString("D");}
        else if(QString(pchar)=="E"){return QString("E");}
        else if(QString(pchar)=="F"){return QString("F");}
        else if(QString(pchar)=="G"){return QString("G");}
        else if(QString(pchar)=="H"){return QString("H");}
        else if(QString(pchar)=="I"){return QString("I");}
        else if(QString(pchar)=="J"){return QString("J");}
        else if(QString(pchar)=="K"){return QString("K");}
        else if(QString(pchar)=="L"){return QString("L");}
        else if(QString(pchar)=="M"){return QString("M");}
        else if(QString(pchar)=="N"){return QString("N");}
        else if(QString(pchar)=="O"){return QString("O");}
        else if(QString(pchar)=="P"){return QString("P");}
        else if(QString(pchar)=="Q"){return QString("Q");}
        else if(QString(pchar)=="R"){return QString("R");}
        else if(QString(pchar)=="S"){return QString("S");}
        else if(QString(pchar)=="T"){return QString("T");}
        else if(QString(pchar)=="U"){return QString("U");}
        else if(QString(pchar)=="V"){return QString("V");}
        else if(QString(pchar)=="W"){return QString("W");}
        else if(QString(pchar)=="X"){return QString("X");}
        else if(QString(pchar)=="Y"){return QString("Y");}
        else if(QString(pchar)=="Z"){return QString("Z");}
        else if(QString(pchar)=="["){return QString("bracketleft");}
        else if(QString(pchar)=="\\"){return QString("backslash");}
        else if(QString(pchar)=="]"){return QString("bracketright");}
        else if(QString(pchar)=="^"){return QString("asciicircum");}
        else if(QString(pchar)=="_"){return QString("underscore");}
        else if(QString(pchar)=="`"){return QString("grave");}
        else if(QString(pchar)=="`"){return QString("quoteleft");}
        else if(QString(pchar)=="a"){return QString("a") ;}
        else if(QString(pchar)=="b"){return QString("b") ;}
        else if(QString(pchar)=="c"){return QString("c") ;}
        else if(QString(pchar)=="d"){return QString("d") ;}
        else if(QString(pchar)=="e"){return QString("e");}
        else if(QString(pchar)=="f"){return QString("f");}
        else if(QString(pchar)=="g"){return QString("g");}
        else if(QString(pchar)=="h"){return QString("h");}
        else if(QString(pchar)=="i"){return QString("i");}
        else if(QString(pchar)=="j"){return QString("j");}
        else if(QString(pchar)=="k"){return QString("k");}
        else if(QString(pchar)=="l"){return QString("l") ;}
        else if(QString(pchar)=="m"){return QString("m")  ;}
        else if(QString(pchar)=="n"){return QString("n")  ;}
        else if(QString(pchar)=="o"){return QString("o") ;}
        else if(QString(pchar)=="p"){return QString("p") ;}
        else if(QString(pchar)=="q"){return QString("q")  ;}
        else if(QString(pchar)=="r"){return QString("r");}
        else if(QString(pchar)=="s"){return QString("s");}
        else if(QString(pchar)=="t"){return QString("t") ;}
        else if(QString(pchar)=="u"){return QString("u") ;}
        else if(QString(pchar)=="v"){return QString("v");}
        else if(QString(pchar)=="w"){return QString("w") ;}
        else if(QString(pchar)=="x"){return QString("x") ;}
        else if(QString(pchar)=="y"){return QString("y") ;}
        else if(QString(pchar)=="z"){return QString("z") ;}
        else if(QString(pchar)=="{"){return QString("braceleft") ;}
        else if(QString(pchar)=="|"){return QString("bar");}
        else if(QString(pchar)=="}"){return QString("braceright");}
        else if(QString(pchar)=="~"){return QString("asciitilde");}
        else return QString(" ");
    }
    void dialogOPT::com2tcpipkeystring(const char *pchar)
    {
        QString strget(pchar);
        QString strsend = "aconsole.click(1);aconsole.doevent();";
        int isize = strget.size();
        for(int i=0;i<isize;i++)
        {
           QString strchar = inputstring(pchar[i]);
           strsend = strsend + QString("aconsole.key(\"")+strchar+QString("\");aconsole.doevent();");
        }
        if(nullptr!=m_pdialog)
            m_pdialog->Com2TcpIpSendString(strsend.toStdString().c_str());

    }
    void dialogOPT::addparservaluestring(const char *pchar)
    {
        QString stradd;
        if(nullptr!=m_pdialog)
              stradd = m_pdialog->getparservaluestring(QString(pchar));
        m_curstr = m_curstr + stradd;
    }
    void dialogOPT::addstring(const char *pchar)
    {
        m_curstr = m_curstr + QString(pchar);
    }
    void dialogOPT::setcurstring(const char *pchar)
    {
        m_curstr = QString(pchar);
    }
    void dialogOPT::com2tcpipcurstring()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->Com2TcpIpSendString(m_curstr.toStdString().c_str());
        m_pdialog->ShowLog(nullptr,m_curstr);
    }
    void dialogOPT::com2tcpipstring(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->Com2TcpIpSendString(pchar);
    }
    void dialogOPT::tcp2comvalue(const char *pvar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2ComSendValue(pvar);
    }
    void dialogOPT::tcp2comimage(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2ComSendImage(pchar);
    }
    void dialogOPT::tcp2tcpimage(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2TcpIpSendImage(pchar);
    }
    void dialogOPT::tcp2tcpvalue(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2TcpIpSendValue(pchar);
    }
    void dialogOPT::tcp2tcpstring(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2TcpIpCompile(pchar);
            //m_pdialog->Send_Control_Multi(QString(pchar));
    }
    void dialogOPT::tcp2comstring(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->TcpIp2ComSendString(pchar);
    }
    void dialogOPT::sendserialfile(const char *pfile)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->sendserialfile(pfile);

    }
    void dialogOPT::runconsole(const char *pchar)
    {
        //if(0!=m_pconsole)
        //    m_pconsole->RunConsole(pchar);
    }
    void dialogOPT::savefile(const char *pchar)
    {
        QDateTime now = QDateTime::currentDateTime();
        QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
        QString strfile = getlocationstringx("./log"+qyearmd+".txt");
            FILE *fp = fopen(strfile.toStdString().c_str(), "at");
            fprintf(fp,pchar);
            fclose(fp);
    }
    void dialogOPT::savevalue(const char *pcharvalue)
    {
        QDateTime now = QDateTime::currentDateTime();
        QString qyearmd = now.toString(QLatin1String("yyyyMMdd"));
        QString strfile = getlocationstringx("./log"+qyearmd+".txt");
            FILE *fp = fopen(strfile.toStdString().c_str(), "at");
            if(nullptr!=m_pdialog)
            {
                QString strv = QString(pcharvalue)+QString("=")+m_pdialog->getparservaluestring(QString(pcharvalue))+QString(";\n\r");

                fprintf(fp,strv.toStdString().c_str());
            }
            fclose(fp);
    }
    void dialogOPT::savekeyvalue(const char *pcharvalue)
    {
        if(nullptr!=m_pdialog)
        {
            QString qfile = getlocationstringx("./keyvalue.cxut");
            QString astr = QString(pcharvalue);
            m_strkeyvalue[astr] = m_pdialog->getparservaluestring(QString(pcharvalue));
           // savefilestring(qfile);
      QString qstrwritestring;
             QMutableMapIterator<QString, QString> ikeyp(m_strkeyvalue);
             while (ikeyp.hasNext()) {
                 ikeyp.next();
                  qstrwritestring = qstrwritestring + ikeyp.key() +  QString("=") + ikeyp.value() + QString(";\n\r");
               //  qDebug() << i.key() << ": " << i.value();
             }

  /*
           QMap<QString, QString>::const_iterator ikeyp = m_strkeyvalue.constBegin();

           while (ikeyp != m_strkeyvalue.constEnd()) {
               qstrwritestring = ikeyp.key() +  QString("=") + ikeyp.value() + QString(";\n\r");
               ++ikeyp;
           }
*/
            QFile f(qfile);

            if ( !f.open(QFile::ReadWrite) )
            {
                return;
            }

            f.write(qstrwritestring.toStdString().c_str());
            f.close();
        }
    }

    double dialogOPT::sinangle(int dangle)
    {
        return sin(dangle);
    }
    double dialogOPT::cosangle(int dangle)
    {
        return cos(dangle);
    }
    void dialogOPT::desktopimagerect(int ix,int iy,int iw,int ih)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->desktopimagerect(ix,iy,iw,ih);
    }
    void dialogOPT::desktopimage()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->desktopimage();
    }
    void dialogOPT::downloadreset()
    {
       // if(0!=m_pdialog)
       //     m_pdialog->settfilefinish();
    }
    void dialogOPT::runcommand(const char *pname)
    {
        if(nullptr!=m_pdialog)
        {
            QString astr(pname);
            m_pdialog->SetCommandEditText(astr);
           // m_pdialog->sendCommand();
        }
    }
    void dialogOPT::runopt(const char *pname)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->runopt(pname);
    }
    void dialogOPT::runstringai()
    {
        if(nullptr!=m_pdialog)
             m_pdialog->runstringai();
    }
    void dialogOPT::pagelistwork(int igap1,int igap2)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->pagelistwork( igap1, igap2);
    }
    void dialogOPT::asleep(int isleeptime)
    {
        //m_time.start();
       // while(m_time.elapsed()<isleeptime)
        //    QCoreApplication::processEvents();
#if defined( Q_OS_WIN )
        QTime time;
        time.restart();
        while (time.elapsed() < isleeptime)
            QCoreApplication::processEvents(QEventLoop::AllEvents, 10);
#else
        QTime time;
        time.restart();
        while (time.elapsed() < isleeptime)
            QCoreApplication::processEvents(QEventLoop::AllEvents, 50);

#endif

    }
    void dialogOPT::scale(double dscale)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->sceneScale(dscale);
    }
    void dialogOPT::rundutylist()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->rundutylist();
    }
    void dialogOPT::cleartab()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->cleartab();
    }
    void dialogOPT::updateview()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->updateview();
    }
    void dialogOPT::flashview()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->flashview();
    }
    void dialogOPT::resetrun()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->resetrun();
    }
    void dialogOPT::TestX()
    {

       QT_TRY {
            int ierror=100/0;
            int *p=0;
            p=p+1;
            p[50]=0;
       }
      QT_CATCH(QString e)
      {

      }



    }
    void dialogOPT::softtrigset(int inum)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->softtrigset(inum);
    }
    void dialogOPT::showdlg(int ishow)
    {
        if(1==ishow)
        {

            if(nullptr!=m_pdialog)
                m_pdialog->showMaximized();
        }
        else if(0==ishow)
        {
            if(nullptr!=m_pdialog)
                m_pdialog->showMinimized();

        }
    }
    void dialogOPT::showlog()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->showmanagelog();
    }
    void dialogOPT::showstring(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->ShowLog(0,QString(pchar));
    }
    void dialogOPT::urlfilter(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->addkeywordfilter(QString(pchar));
    }
    void dialogOPT::filextfilter(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->addextfilter(QString(pchar));
    }
    void dialogOPT::urlneedstring(const char *pchar)
    {
        if(nullptr!=m_pdialog)
            m_pdialog->addneedstringlist(QString(pchar));

    }
    void dialogOPT::clearfilter()
    {
        if(nullptr!=m_pdialog)
            m_pdialog->clearfilter();

    }
    void dialogOPT::showdebug(int ishow)
    {
        m_pdialog->showdebug(ishow);

    }
    void dialogOPT::showcustom(int ishow)
    {
        m_pdialog->showcustom(ishow);
    }
    void dialogOPT::CamTest()
    {
     //   w.show();
    }
    void dialogOPT::modbus(const char *pipchar)
    {
        m_strip_modbus = QString(pipchar);

    }
    void dialogOPT::modbustcp()
    {
        if(nullptr==m_modbustcpi1)
        {
            m_modbustcpi1 = new ModBusWidget;
            m_modbustcpi1->hide();
        }
        if(nullptr==m_modbustcpi2)
        {
            m_modbustcpi2 = new ModBusWidget;
            m_modbustcpi2->hide();
        }
        if(nullptr==m_modbustcpi3)
        {
            m_modbustcpi3 = new ModBusWidget;
            m_modbustcpi3->hide();
        }
        if(nullptr==m_modbustcpw1)
        {
            m_modbustcpw1 = new ModBusWidget;
            m_modbustcpw1->hide();
        }
        if(nullptr==m_modbustcpw2)
        {
            m_modbustcpw2 = new ModBusWidget;
            m_modbustcpw2->hide();
        }
        if(nullptr==m_modbustcpw3)
        {
            m_modbustcpw3 = new ModBusWidget;
            m_modbustcpw3->hide();
        }
        if(nullptr!=m_modbustcpw1
                &&nullptr!=m_modbustcpw2
                &&nullptr!=m_modbustcpw3
                &&nullptr!=m_modbustcpi1
                &&nullptr!=m_modbustcpi2
                &&nullptr!=m_modbustcpi3)
        {
            m_modbustcpi1->SetWH(m_modbustcpw1);
            m_modbustcpi1->SetDialog(m_pdialog);
            m_modbustcpi1->FuncCodeSetNumLineEdit(1);

            m_modbustcpi2->SetWH(m_modbustcpw2);
            m_modbustcpi2->SetDialog(m_pdialog);
            m_modbustcpi2->FuncCodeSetNumLineEdit(1);

            m_modbustcpi3->SetWH(m_modbustcpw3);
            m_modbustcpi3->SetDialog(m_pdialog);
            m_modbustcpi3->FuncCodeSetNumLineEdit(1);
        }
    }

    void dialogOPT::modbustcpshow()
    {
        if(nullptr!=m_modbustcpi1)
        {
            m_modbustcpi1->show();
        }
        if(nullptr!=m_modbustcpi2)
        {
            m_modbustcpi2->show();
        }
        if(nullptr!=m_modbustcpi3)
        {
            m_modbustcpi3->show();
        }
        if(nullptr!=m_modbustcpw1)
        {
            m_modbustcpw1->show();
        }
        if(nullptr!=m_modbustcpw2)
        {
            m_modbustcpw2->show();
        }
        if(nullptr!=m_modbustcpw3)
        {
            m_modbustcpw3->show();
        }
    }
    void dialogOPT::modbustcpconnect()
    {
        if(nullptr!=m_modbustcpi1)
        {
            m_modbustcpi1->TcpConnect();
        }
        if(nullptr!=m_modbustcpi2)
        {
            m_modbustcpi2->TcpConnect();
        }
        if(nullptr!=m_modbustcpi3)
        {
            m_modbustcpi3->TcpConnect();
        }
        if(nullptr!=m_modbustcpw1)
        {
            m_modbustcpw1->TcpConnect();
        }
        if(nullptr!=m_modbustcpw2)
        {
            m_modbustcpw2->TcpConnect();
        }
        if(nullptr!=m_modbustcpw3)
        {
            m_modbustcpw3->TcpConnect();
        }
    }
   /* void dialogOPT::modbustcpreadregisters(int inum,int ivalue)
    {
        if(nullptr!=m_modbustcpi1)
        {
           // SetValue
            QString strnum = QString("%1").arg(inum);
            QString strvalue = QString("%1").arg(ivalue);
            m_modbustcpi1->SetValue(strnum,strvalue);
            m_modbustcpi1->ReadRegValue(strnum,strvalue);
            m_modbustcpi1->FuncCodeSetNumLineEdit(1);
            m_modbustcpi1->TCPRequestMessage(1);
        }
    }*/

    int dialogOPT::modbustcpgetvalue(int inum)
    {
       return m_modbustcpi1->GetRegValue(inum);
    }
    void dialogOPT::modbustcpsetinputimer(int inputnum,int itimes)
    {
        if(1==inputnum)
            m_modbustcpi1->SetInputTimer(1,itimes);
        if(2==inputnum)
            m_modbustcpi2->SetInputTimer(2,itimes);
        if(3==inputnum)
            m_modbustcpi3->SetInputTimer(3,itimes);

    }
    void dialogOPT::modbustcpwriteregisters(int inum,int isum,int ivalue)
    {
        if(nullptr!=m_modbustcpw1)
        {
           // SetValue
            QString strnum = QString("%1").arg(inum);
            QString strvalue = QString("%1").arg(isum);
            QString strregnum = QString("%1").arg(ivalue);
            m_modbustcpw1->SetValue(strnum,strvalue);
            m_modbustcpw1->WriteRegValue(strnum,strvalue,strregnum);
            m_modbustcpw1->FuncCodeSetNumLineEdit(3);
            m_modbustcpw1->TCPRequestMessage(3);
        }
    }



    void dialogOPT::setmodbus()
    {

    }
    void dialogOPT::runmodbustimer(int mtime)
    {

    }
    void dialogOPT::stopmodbustimer()
    {

    }
    void dialogOPT::setmodbustrig(int itrg,int inum)
    {

    }
    void dialogOPT::setmodbustrigrun0(const char *pchar)
    {

    }
    void dialogOPT::setmodbustrigrun1(const char *pchar)
    {

    }
    void dialogOPT::setmodbustrigrun2(const char *pchar)
    {
        }
    void dialogOPT::resetmodbus()
    {
    }



    void dialogOPT::setmodbusoutput(int inum,int ivalue)
    {

    }
    void dialogOPT::modbusoutput()
    {

    }
    void dialogOPT::connect2PLC(const char *pipchar)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr==m_plc_input)
            m_plc_input=new PLC(pipchar,1);
        if(nullptr==m_plc_output)
            m_plc_output=new PLC(pipchar,0);
    }
    void dialogOPT::setplcip(const char *pchar)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_output)
            m_plc_output->setip(pchar);
        if(nullptr!=m_plc_input)
            m_plc_input->setip(pchar);
    }
    void dialogOPT::setplcport(int port)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
            m_plc_input->setport(port);
        if(nullptr!=m_plc_output)
            m_plc_output->setport(port);
    }
    void dialogOPT::runplctimer(int mtime)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
            m_plc_input->startrun(mtime);
        if(nullptr!=m_plc_output)
            m_plc_output->startrun(mtime);
    }
    void dialogOPT::stopplctimer()
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_output)
            m_plc_output->stoprun();
        if(nullptr!=m_plc_input)
            m_plc_input->stoprun();
    }
    void dialogOPT::setplctrig(int itrg,int inum)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
            m_plc_input->settrig(itrg,inum);

    }

    void dialogOPT::write2PLC(int iadress,int ivalue)
    {
        if(nullptr!=m_plc_output)
        {
            m_plc_output->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_input)
        {
            m_plc_input->setdialog(m_pdialog);
        }
        if(nullptr!=m_plc_output)
           if(nullptr!=m_pdialog)
           {
                m_pdialog->ShowLog(nullptr,m_plc_output->Write(iadress,ivalue) );
           }
    }

    void dialogOPT::setplctrigrun0(const char *pchar)
    {
        if(nullptr!=m_plc_input)
            m_plc_input->settrigrun(0,pchar);
    }
    void dialogOPT::setplctrigrun1(const char *pchar)
    {
        if(nullptr!=m_plc_input)
            m_plc_input->settrigrun(1,pchar);
    }
    void dialogOPT::setplctrigrun2(const char *pchar)
    {
        if(nullptr!=m_plc_input)
            m_plc_input->settrigrun(2,pchar);
    }
    void dialogOPT::startslave()
    {
        if(nullptr==m_serialportslave)
        {

            m_serialportslave=new SerialportSlaveDialog;
            if(nullptr!=m_pdialog)
            {
                m_serialportslave->setdialog(m_pdialog);
            }
            m_serialportslave->startSlave();
            m_serialportslave->hide();
        }
    }
    void dialogOPT::showslave(int ishow)
    {
        if(nullptr!=m_serialportslave)
         {
            if(ishow>0)
            m_serialportslave->show();
            else
                m_serialportslave->hide();

        }
    }



